text stringlengths 6 9.38M |
|---|
-- You can use this file to load seed data into the database using SQL statements
insert into Perfil (id, descricao, icativo) values (NEXTVAL('seq_perfil'), 'Adminstrador', true)
insert into Perfil (id, descricao, icativo) values (NEXTVAL('seq_perfil'), 'Gestor do Sistema', true)
insert into Perfil (id, descricao, icativo) values (NEXTVAL('seq_perfil'), 'Tester', true) |
DELIMITER //
CREATE PROCEDURE gen_dictionary_proc(dictionary_name VARCHAR(32))
BEGIN
/* 1. Get maximum identifier from the dictionary table */
SET @get_max_id_sttmnt_str := CONCAT('SELECT MAX(id) INTO @gen_dictionary_maxid FROM gen_dictionary_', dictionary_name);
PREPARE get_max_id_sttmnt FROM @get_max_id_sttmnt_str;
EXECUTE get_max_id_sttmnt;
DEALLOCATE PREPARE get_max_id_sttmnt;
/* 2. Raad a random value from the dictionary */
IF @gen_dictionary_maxid IS NOT NULL THEN
SET @rnd_id := gen_range(1, @gen_dictionary_maxid);
SET @gen_dict_rnd_sttmnt_str := CONCAT('SELECT val INTO @gen_dictionary_value FROM gen_dictionary_', dictionary_name);
SET @gen_dict_rnd_sttmnt_str := CONCAT(@gen_dict_rnd_sttmnt_str, ' WHERE id = ?');
PREPARE gen_dict_rnd_sttmnt FROM @gen_dict_rnd_sttmnt_str;
EXECUTE gen_dict_rnd_sttmnt USING @rnd_id;
DEALLOCATE PREPARE gen_dict_rnd_sttmnt;
END IF;
END //
DELIMITER ;
|
--
-- Structure for table forms_form
--
DROP TABLE IF EXISTS forms_breadcrumbaccordion_config_item;
CREATE TABLE forms_breadcrumbaccordion_config_item
(
id_form INT DEFAULT 0 NOT NULL,
id_step INT DEFAULT 0 NOT NULL,
position INT DEFAULT 0 NOT NULL,
PRIMARY KEY (id_form, id_step)
); |
/*
insert into news_source values
(DEFAULT, 'IPS', 17650854, DEFAULT, DEFAULT, '{"ipsnews\\.net"}', 'en');
insert into news_source values
(DEFAULT, 'IPS', 42420705, DEFAULT, DEFAULT, '{"ipsnoticias\\.net"}', 'es');
insert into news_source values
(DEFAULT, 'ABR', 876255914235494400, DEFAULT, DEFAULT, '{"agenciabrasil\\.ebc\\.com\\.br/en"}', 'en');
insert into news_source values
(DEFAULT, 'ABR', 876256940401328129, DEFAULT, DEFAULT, '{"agenciabrasil\\.ebc\\.com\\.br/es"}', 'es');
insert into news_source values
(DEFAULT, 'TASS', 1903712426, DEFAULT, DEFAULT, '{"tass\\.com"}', 'en');
insert into news_source values
(DEFAULT, 'PTI', 876258514049617920, DEFAULT, DEFAULT, '{"ptinews\\.com/news"}', 'en');
insert into news_source values
(DEFAULT, 'XNN', 487118986, DEFAULT, DEFAULT, '{"news\\.xinhuanet\\.com/english"}', 'en');
insert into news_source values
(DEFAULT, 'XNN', 722950850, DEFAULT, DEFAULT, '{"spanish\\.xinhuanet\\.com"}', 'es');
*/
do $$
declare news_source_id integer;
begin
news_source_id := (select id from news_source where name = 'ABR' and locale = 'en');
insert into news_integration values
(
DEFAULT,
'rss',
'{"url": "http://agenciabrasil.ebc.com.br/en/rss/ultimasnoticias/feed.xml", "maxCacheSize": 15}'::json,
'nw_abr_en',
news_source_id,
DEFAULT,
DEFAULT
);
news_source_id := (select id from news_source where name = 'ABR' and locale = 'es');
insert into news_integration values
(
DEFAULT,
'rss',
'{"url": "http://agenciabrasil.ebc.com.br/es/rss/ultimasnoticias/feed.xml", "maxCacheSize": 15}'::json,
'nw_abr_es',
news_source_id,
DEFAULT,
DEFAULT
);
news_source_id := (select id from news_source where name = 'PTI' and locale = 'en');
insert into news_integration values
(
DEFAULT,
'web',
'{"url": "http://www.ptinews.com/", "linkSelector": ".catLatestHeadli", "maxCacheSize": 6}'::json,
'nw_pti_en',
news_source_id,
DEFAULT,
DEFAULT
);
end
$$
|
--
-- PostgreSQL database ksamsok
--
CREATE DATABASE ksamsok
WITH OWNER = "ksamsok_adm"
ENCODING = 'UTF8'
LC_COLLATE = 'sv_SE.UTF-8'
LC_CTYPE = 'sv_SE.UTF-8'
TABLESPACE = pg_default
CONNECTION LIMIT = -1;
REVOKE ALL ON DATABASE ksamsok FROM public; -- see notes below!
GRANT CONNECT ON DATABASE ksamsok TO ksamsok_read; -- others inherit
\connect ksamsok;
-- CREATE SCHEMA ksamsok AUTHORIZATION lamning_adm;
DROP SCHEMA public;
CREATE SCHEMA ksamsok AUTHORIZATION ksamsok_adm;
SET search_path = ksamsok;
-- CREATE SCHEMA ksamsok AUTHORIZATION ksamsok;
ALTER ROLE ksamsok_adm IN DATABASE ksamsok SET search_path = ksamsok;
ALTER ROLE ksamsok_read IN DATABASE ksamsok SET search_path = ksamsok;
ALTER ROLE ksamsok_usr IN DATABASE ksamsok SET search_path = ksamsok;
GRANT USAGE ON SCHEMA ksamsok TO ksamsok_read;
GRANT CREATE ON SCHEMA ksamsok TO ksamsok_adm;
ALTER DEFAULT PRIVILEGES FOR ROLE ksamsok_adm
GRANT SELECT ON TABLES TO ksamsok_read;
ALTER DEFAULT PRIVILEGES FOR ROLE ksamsok_adm
GRANT INSERT, UPDATE, DELETE, TRUNCATE ON TABLES TO ksamsok_usr;
ALTER DEFAULT PRIVILEGES FOR ROLE ksamsok_adm
GRANT USAGE, SELECT, UPDATE ON SEQUENCES TO ksamsok_usr;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
SET statement_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = off;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET escape_string_warning = off;
SET search_path = public, pg_catalog;
SET search_path = public, pg_catalog;
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: content; Type: TABLE; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
CREATE TABLE ksamsok.content (
uri character varying(1024) NOT NULL,
oaiuri character varying(1024),
serviceid character varying(20),
xmldata text,
changed timestamp without time zone,
added timestamp without time zone,
deleted timestamp without time zone,
datestamp timestamp without time zone NOT NULL,
status bigint,
idnum bigint NOT NULL,
nativeurl character varying(1024)
);
ALTER TABLE ksamsok.content OWNER TO ksamsok_adm;
--
-- Name: ksamsok.content_idnum_seq; Type: SEQUENCE; Schema: ksamsok; Owner: ksamsok_adm
--
CREATE SEQUENCE ksamsok.content_idnum_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE ksamsok.content_idnum_seq OWNER TO ksamsok_adm;
--
-- Name: ksamsok.content_idnum_seq; Type: SEQUENCE OWNED BY; Schema: ksamsok; Owner: ksamsok_adm
--
ALTER SEQUENCE ksamsok.content_idnum_seq OWNED BY ksamsok.content.idnum;
--
-- Name: harvestservices; Type: TABLE; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
CREATE TABLE ksamsok.harvestservices (
serviceid character varying(20) NOT NULL,
servicetype character varying(20),
name character varying(200),
harvesturl character varying(4000),
harvestsetspec character varying(50),
cronstring character varying(50),
lastharvestdate timestamp without time zone,
alwayseverything boolean,
firstindexdate timestamp without time zone,
kortnamn character varying(20),
beskrivning character varying(2000),
paused boolean
);
ALTER TABLE ksamsok.harvestservices OWNER TO ksamsok_adm;
--
-- Name: organisation; Type: TABLE; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
CREATE TABLE ksamsok.organisation (
kortnamn character varying(20) NOT NULL,
beskrivswe character varying(2000),
beskriveng character varying(2000),
adress1 character varying(32),
adress2 character varying(32),
postadress character varying(32),
kontaktperson character varying(32),
epostkontaktperson character varying(256),
websida character varying(256),
websidaks character varying(256),
lowressurl character varying(256),
thumbnailurl character varying(256),
namnswe character varying(100),
namneng character varying(100),
pass character varying(30),
serv_org character varying(20)
);
ALTER TABLE ksamsok.organisation OWNER TO ksamsok_adm;
--
-- Name: servicelog; Type: TABLE; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
CREATE TABLE ksamsok.servicelog (
serviceid character varying(20),
eventtype bigint,
eventstep character varying(20),
eventts timestamp without time zone,
message character varying(4000),
eventid bigint NOT NULL
);
ALTER TABLE ksamsok.servicelog OWNER TO ksamsok_adm;
--
-- Name: servicelog_eventid_seq; Type: SEQUENCE; Schema: ksamsok; Owner: ksamsok_adm
--
CREATE SEQUENCE ksamsok.servicelog_eventid_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE ksamsok.servicelog_eventid_seq OWNER TO ksamsok_adm;
--
-- Name: servicelog_eventid_seq; Type: SEQUENCE OWNED BY; Schema: ksamsok; Owner: ksamsok_adm
--
ALTER SEQUENCE ksamsok.servicelog_eventid_seq OWNED BY ksamsok.servicelog.eventid;
--
-- Name: idnum; Type: DEFAULT; Schema: ksamsok; Owner: ksamsok_adm
--
ALTER TABLE ksamsok.content ALTER COLUMN idnum SET DEFAULT nextval('ksamsok.content_idnum_seq'::regclass);
--
-- Name: eventid; Type: DEFAULT; Schema: ksamsok; Owner: ksamsok_adm
--
ALTER TABLE ksamsok.servicelog ALTER COLUMN eventid SET DEFAULT nextval('ksamsok.servicelog_eventid_seq'::regclass);
--
-- Name: content_pkey; Type: CONSTRAINT; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
ALTER TABLE ONLY ksamsok.content
ADD CONSTRAINT content_pkey PRIMARY KEY (uri);
--
-- Name: organisation_pkey; Type: CONSTRAINT; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
ALTER TABLE ONLY ksamsok.organisation
ADD CONSTRAINT organisation_pkey PRIMARY KEY (kortnamn);
--
-- Name: pk_harvestservices; Type: CONSTRAINT; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
ALTER TABLE ONLY ksamsok.harvestservices
ADD CONSTRAINT pk_harvestservices PRIMARY KEY (serviceid);
--
-- Name: pk_servicelog; Type: CONSTRAINT; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
ALTER TABLE ONLY ksamsok.servicelog
ADD CONSTRAINT pk_servicelog PRIMARY KEY (eventid);
--
-- Name: ix_content_deleted; Type: INDEX; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
CREATE INDEX ix_content_deleted ON ksamsok.content USING btree (deleted);
--
-- Name: ix_content_oai; Type: INDEX; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
CREATE INDEX ix_content_oai ON ksamsok.content USING btree (oaiuri);
--
-- Name: ix_content_serv; Type: INDEX; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
CREATE INDEX ix_content_serv ON ksamsok.content USING btree (serviceid);
--
-- Name: ix_content_serv_changed; Type: INDEX; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
CREATE INDEX ix_content_serv_changed ON ksamsok.content USING btree (serviceid, changed);
--
-- Name: ix_content_serv_deleted; Type: INDEX; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
CREATE INDEX ix_content_serv_deleted ON ksamsok.content USING btree (serviceid, deleted);
--
-- Name: ix_content_serv_deleted_uri; Type: INDEX; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
CREATE INDEX ix_content_serv_deleted_uri ON ksamsok.content USING btree (serviceid, uri) WHERE (deleted IS NULL);
--
-- Name: ix_content_uri_serv; Type: INDEX; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
CREATE INDEX ix_content_uri_serv ON ksamsok.content USING btree (uri, serviceid);
--
-- Name: ix_servicelog_serv; Type: INDEX; Schema: ksamsok; Owner: ksamsok_adm; Tablespace:
--
CREATE INDEX ix_servicelog_serv ON ksamsok.servicelog USING btree (serviceid);
--
-- Name: fk_kortnamn_organisation; Type: FK CONSTRAINT; Schema: ksamsok; Owner: ksamsok_adm
--
ALTER TABLE ONLY ksamsok.harvestservices
ADD CONSTRAINT fk_kortnamn_organisation FOREIGN KEY (kortnamn) REFERENCES ksamsok.organisation(kortnamn);
--
-- Name: ksamsok; Type: ACL; Schema: -; Owner: ksamsok_adm
--
REVOKE ALL ON SCHEMA ksamsok FROM ksamsok_adm;
GRANT ALL ON SCHEMA ksamsok TO ksamsok_adm;
--
-- Name: content; Type: ACL; Schema: ksamsok; Owner: ksamsok_adm
--
-- REVOKE ALL ON TABLE content FROM ksamsok;
REVOKE ALL ON TABLE ksamsok.content FROM ksamsok_adm;
GRANT SELECT,INSERT,DELETE,UPDATE ON TABLE ksamsok.content TO ksamsok_adm;
GRANT ALL ON TABLE ksamsok.content TO ksamsok_adm;
--
-- Name: ksamsok.content_idnum_seq; Type: ACL; Schema: ksamsok; Owner: ksamsok_adm
--
REVOKE ALL ON SEQUENCE ksamsok.content_idnum_seq FROM ksamsok_adm;
GRANT ALL ON SEQUENCE ksamsok.content_idnum_seq TO ksamsok_adm;
GRANT SELECT,UPDATE ON SEQUENCE ksamsok.content_idnum_seq TO ksamsok_adm;
--
-- Name: harvestservices; Type: ACL; Schema: ksamsok; Owner: ksamsok_adm
--
-- REVOKE ALL ON TABLE harvestservices FROM ksamsok;
REVOKE ALL ON TABLE ksamsok.harvestservices FROM ksamsok_adm;
GRANT SELECT,INSERT,DELETE,UPDATE ON TABLE ksamsok.harvestservices TO ksamsok_adm;
GRANT ALL ON TABLE ksamsok.harvestservices TO ksamsok_adm;
--
-- Name: organisation; Type: ACL; Schema: ksamsok; Owner: ksamsok_adm
--
REVOKE ALL ON TABLE ksamsok.organisation FROM ksamsok_adm;
GRANT SELECT,INSERT,DELETE,UPDATE ON TABLE ksamsok.organisation TO ksamsok_adm;
GRANT ALL ON TABLE ksamsok.organisation TO ksamsok_adm;
--
-- Name: servicelog; Type: ACL; Schema: ksamsok; Owner: ksamsok_adm
--
REVOKE ALL ON TABLE ksamsok.servicelog FROM ksamsok_adm;
GRANT SELECT,INSERT,DELETE,UPDATE ON TABLE ksamsok.servicelog TO ksamsok_adm;
GRANT ALL ON TABLE ksamsok.servicelog TO ksamsok_adm;
--
-- Name: servicelog_eventid_seq; Type: ACL; Schema: ksamsok; Owner: ksamsok_adm
--
REVOKE ALL ON SEQUENCE ksamsok.servicelog_eventid_seq FROM ksamsok_adm;
GRANT ALL ON SEQUENCE ksamsok.servicelog_eventid_seq TO ksamsok_adm;
GRANT SELECT,UPDATE ON SEQUENCE ksamsok.servicelog_eventid_seq TO ksamsok_adm;
--
-- Name: DEFAULT PRIVILEGES FOR SEQUENCES; Type: DEFAULT ACL; Schema: -; Owner: ksamsok_adm
--
ALTER DEFAULT PRIVILEGES FOR ROLE ksamsok_adm GRANT SELECT,UPDATE ON SEQUENCES TO ksamsok_adm;
--
-- Name: DEFAULT PRIVILEGES FOR FUNCTIONS; Type: DEFAULT ACL; Schema: -; Owner: ksamsok_adm
--
ALTER DEFAULT PRIVILEGES FOR ROLE ksamsok_adm REVOKE ALL ON FUNCTIONS FROM ksamsok_adm;
ALTER DEFAULT PRIVILEGES FOR ROLE ksamsok_adm GRANT ALL ON FUNCTIONS TO ksamsok_adm;
--
-- Name: DEFAULT PRIVILEGES FOR TABLES; Type: DEFAULT ACL; Schema: -; Owner: ksamsok_adm
--
ALTER DEFAULT PRIVILEGES FOR ROLE ksamsok_adm GRANT SELECT,INSERT,DELETE,UPDATE ON TABLES TO ksamsok_adm;
--
-- PostgreSQL database ksamsok complete
--
GRANT SELECT ON ALL TABLES IN SCHEMA ksamsok TO ksamsok_read;
GRANT INSERT, UPDATE, DELETE, TRUNCATE ON ALL TABLES IN SCHEMA ksamsok TO ksamsok_usr;
GRANT USAGE, SELECT, UPDATE ON ALL SEQUENCES IN SCHEMA ksamsok TO ksamsok_usr;
|
CREATE DEFINER=`root`@`localhost` PROCEDURE `editCustomerAddress`(
IN customeraddresstype VARCHAR(100),
IN houseno VARCHAR(6),
IN addressline1 VARCHAR(200),
IN addressline2 VARCHAR(200),
IN city VARCHAR(200),
IN state VARCHAR(200),
IN country VARCHAR(200),
IN zipcode VARCHAR(6),
IN modifiedby VARCHAR(100),
IN id INT(11)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
END;
START TRANSACTION;
UPDATE customeraddress SET
customeraddresstype = customeraddresstype,
houseno = houseno,
addressline1 = addressline1,
addressline2 = addressline2,
city = city,
state = state,
country = country,
zipcode = zipcode,
modifiedby = modifiedby
WHERE customeraddressid = id;
COMMIT;
END |
-- phpMyAdmin SQL Dump
-- version 4.0.10deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Mar 08, 2016 at 04:36 PM
-- Server version: 5.5.47-0ubuntu0.14.04.1
-- PHP Version: 5.5.9-1ubuntu4.14
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `testing`
--
-- --------------------------------------------------------
--
-- Table structure for table `answers`
--
CREATE TABLE IF NOT EXISTS `answers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`question_id` int(11) NOT NULL,
`answer` longtext COLLATE utf8_unicode_ci NOT NULL,
`is_right` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_50D0C6061E27F6BF` (`question_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=54 ;
--
-- Dumping data for table `answers`
--
INSERT INTO `answers` (`id`, `question_id`, `answer`, `is_right`) VALUES
(1, 1, '46', 0),
(2, 1, '47', 0),
(3, 1, '49', 0),
(4, 1, '50', 0),
(5, 1, '48', 1),
(6, 2, 'ТИГР', 0),
(7, 2, 'ЛЕВ', 0),
(8, 2, 'ГЕПАРД', 0),
(9, 2, 'ВОЛК', 1),
(10, 2, 'РЫСЬ', 0),
(11, 3, 'ТРАНСПОРТ', 0),
(12, 3, 'ЖИВОТНОЕ', 0),
(13, 3, 'ПЕРИОД', 1),
(14, 3, 'ДЕРЕВО', 0),
(15, 3, 'ЦВЕТОК', 0),
(16, 4, 'И С', 1),
(17, 4, 'И Р', 0),
(18, 4, 'Й С', 0),
(19, 4, 'К Т', 0),
(20, 4, 'З Р', 0),
(21, 5, '35', 0),
(22, 5, '37', 1),
(23, 5, '41', 0),
(24, 5, '42', 0),
(25, 5, '43', 0),
(26, 6, '2 и 9', 0),
(27, 6, '3 и 8', 1),
(28, 6, '1 и 2', 0),
(29, 6, '4 и 5', 0),
(30, 6, '6 и 7', 0),
(31, 7, '32 26', 0),
(32, 7, '46 32', 0),
(33, 7, '48 30', 0),
(34, 7, '46 30', 0),
(35, 7, '48 32', 1),
(36, 8, 'ФРАНЦИЯ', 0),
(37, 8, 'ГЕРМАНИЯ', 1),
(38, 8, 'США', 0),
(39, 8, 'ШВЕЙЦАРИЯ', 0),
(40, 8, 'КАНАДА', 0),
(41, 9, 'РЕНТА ХИЗАМ', 0),
(42, 9, 'РАЗ О', 0),
(43, 9, 'УДИЛА ГОЛ С', 0),
(44, 9, 'ПЕТЬ РОК МЮ', 1),
(45, 9, 'Ц НАС РИС', 0),
(46, 10, 'Леденец', 0),
(47, 10, 'Булка', 0),
(48, 10, 'Доска', 0),
(49, 10, 'Мотоцикл', 0),
(50, 10, 'Дерево', 0),
(51, 10, 'Смартфон', 0),
(52, 10, 'Бенефис', 1),
(53, 10, 'Бикини', 0);
-- --------------------------------------------------------
--
-- Table structure for table `people`
--
CREATE TABLE IF NOT EXISTS `people` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`test_id` int(11) NOT NULL,
`name` varchar(300) COLLATE utf8_unicode_ci NOT NULL,
`finished` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_28166A261E5D0459` (`test_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=12 ;
--
-- Dumping data for table `people`
--
INSERT INTO `people` (`id`, `test_id`, `name`, `finished`) VALUES
(1, 1, 'test', NULL),
(2, 1, 'dfgbfd', NULL),
(3, 1, 'sdfsdfsdf', NULL),
(4, 1, 'sdfsdfsdf', NULL),
(5, 1, 'asd', NULL),
(6, 1, 'asdasdasd', NULL),
(7, 1, 'test', NULL),
(8, 1, 'test', NULL),
(9, 1, 'еуы', NULL),
(10, 1, 'ali', NULL),
(11, 1, 'testUser', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `people_answers`
--
CREATE TABLE IF NOT EXISTS `people_answers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`people_id` int(11) NOT NULL,
`question_id` int(11) NOT NULL,
`answer_id` int(11) NOT NULL,
`answer_time` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_1079DA423147C936` (`people_id`),
KEY `IDX_1079DA421E27F6BF` (`question_id`),
KEY `IDX_1079DA42AA334807` (`answer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=25 ;
--
-- Dumping data for table `people_answers`
--
INSERT INTO `people_answers` (`id`, `people_id`, `question_id`, `answer_id`, `answer_time`) VALUES
(1, 9, 1, 5, '2016-03-07 18:55:05'),
(2, 9, 7, 34, '2016-03-07 18:52:09'),
(3, 9, 8, 39, '2016-03-07 18:52:12'),
(4, 9, 9, 41, '2016-03-07 18:52:16'),
(5, 10, 1, 5, '2016-03-08 14:19:45'),
(6, 10, 9, 43, '2016-03-08 14:23:53'),
(7, 10, 2, 9, '2016-03-08 14:25:00'),
(8, 10, 3, 14, '2016-03-08 14:51:28'),
(9, 10, 4, 19, '2016-03-08 14:51:31'),
(10, 10, 5, 21, '2016-03-08 15:01:58'),
(11, 10, 6, 28, '2016-03-08 15:02:03'),
(12, 10, 7, 32, '2016-03-08 15:02:08'),
(13, 10, 8, 37, '2016-03-08 15:02:12'),
(14, 10, 10, 52, '2016-03-08 15:02:17'),
(15, 11, 1, 1, '2016-03-08 16:17:51'),
(16, 11, 2, 9, '2016-03-08 16:17:56'),
(17, 11, 3, 13, '2016-03-08 16:18:06'),
(18, 11, 4, 19, '2016-03-08 16:18:19'),
(19, 11, 5, 24, '2016-03-08 16:18:29'),
(20, 11, 6, 27, '2016-03-08 16:19:01'),
(21, 11, 7, 34, '2016-03-08 16:19:13'),
(22, 11, 8, 37, '2016-03-08 16:19:17'),
(23, 11, 9, 44, '2016-03-08 16:19:31'),
(24, 11, 10, 52, '2016-03-08 16:20:41');
-- --------------------------------------------------------
--
-- Table structure for table `questions`
--
CREATE TABLE IF NOT EXISTS `questions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`test_id` int(11) NOT NULL,
`question` longtext COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_8ADC54D51E5D0459` (`test_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=11 ;
--
-- Dumping data for table `questions`
--
INSERT INTO `questions` (`id`, `test_id`, `question`) VALUES
(1, 1, 'Каким числом следует заменить знак вопроса?\r\n23 28 33 38 43 ?'),
(2, 1, 'Что здесь является лишним?'),
(3, 1, 'Какое слово надо вставить в скобки, чтобы закончить первое слово и начать последнее слово? Что обозначает слово в скобках?<br/>\r\n<b>ЧЕЛО ( . . . ) СЕЛЬ</b>'),
(4, 1, 'Какие две буквы должны идти далее?<br>\r\n<b> А И Г Л Ё О ? ? </b>'),
(5, 1, 'Каким числом следует заменить знак вопроса?<br/>\r\n<b>\r\n 3 8 6 30 <br/>\r\n4 9 3 39 <br/>\r\n7 5 2 ?</b>'),
(6, 1, 'Какие два слова наиболее противоположны по смыслу?\r\n<p>1) БОЛЬШОЙ</p>\r\n<p>2) ШИРОКИЙ</p>\r\n<p>3) УНИЖАТЬ</p>\r\n<p>4) ВЫЗЫВАЮЩИЙ</p>\r\n<p>5) ДРОЖЖАТЬ</p>\r\n<p>6) ПЛАЧЕВНЫЙ</p>\r\n<p>7) КРИЧАТЬ</p>\r\n<p>8) ХВАЛИТЬ</p>\r\n<p>9) ТОЛСТЫЙ</p>'),
(7, 1, 'Какими двумя числами следует заменить знаки вопроса?\r\n<br>\r\n4 12 8 24 16 ? ?'),
(8, 1, 'Определите название города, зашифрованного в анаграмме. В какой стране находится этот город?\r\n <br>НХЮМ НЕ'),
(9, 1, 'Какое слово не является анаграммой цветов?'),
(10, 1, 'Какое слово является лишним?\r\n ШОКОЛАД : Леденец Булка Доска Мотоцикл Дерево Смартфон Бенефис Бикини');
-- --------------------------------------------------------
--
-- Table structure for table `tests`
--
CREATE TABLE IF NOT EXISTS `tests` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(300) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2 ;
--
-- Dumping data for table `tests`
--
INSERT INTO `tests` (`id`, `name`) VALUES
(1, 'iq тест № 1');
--
-- Constraints for dumped tables
--
--
-- Constraints for table `answers`
--
ALTER TABLE `answers`
ADD CONSTRAINT `FK_50D0C6061E27F6BF` FOREIGN KEY (`question_id`) REFERENCES `questions` (`id`) ON DELETE CASCADE;
--
-- Constraints for table `people`
--
ALTER TABLE `people`
ADD CONSTRAINT `FK_28166A261E5D0459` FOREIGN KEY (`test_id`) REFERENCES `tests` (`id`) ON DELETE CASCADE;
--
-- Constraints for table `people_answers`
--
ALTER TABLE `people_answers`
ADD CONSTRAINT `FK_1079DA421E27F6BF` FOREIGN KEY (`question_id`) REFERENCES `questions` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `FK_1079DA423147C936` FOREIGN KEY (`people_id`) REFERENCES `people` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `FK_1079DA42AA334807` FOREIGN KEY (`answer_id`) REFERENCES `answers` (`id`) ON DELETE CASCADE;
--
-- Constraints for table `questions`
--
ALTER TABLE `questions`
ADD CONSTRAINT `FK_8ADC54D51E5D0459` FOREIGN KEY (`test_id`) REFERENCES `tests` (`id`) ON DELETE CASCADE;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
--
-- Script was generated by Devart dbForge Studio 2019 for MySQL, Version 8.2.23.0
-- Product home page: http://www.devart.com/dbforge/mysql/studio
-- Script date 24/11/2019 15:53:34
-- Server version: 8.0.13-4
-- Client version: 4.1
--
--
-- Disable foreign keys
--
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
--
-- Set SQL mode
--
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
--
-- Set character set the client will use to send SQL statements to the server
--
SET NAMES 'utf8';
DROP DATABASE IF EXISTS `53WNcTU5Dt`;
CREATE DATABASE IF NOT EXISTS `53WNcTU5Dt`
CHARACTER SET utf8
COLLATE utf8_unicode_ci;
--
-- Set default database
--
USE `53WNcTU5Dt`;
--
-- Create table `tblusers`
--
CREATE TABLE IF NOT EXISTS tblusers (
userID INT(11) NOT NULL AUTO_INCREMENT,
userName VARCHAR(255) NOT NULL,
userFirstName VARCHAR(255) NOT NULL,
userLastName VARCHAR(255) NOT NULL,
userEmail VARCHAR(255) NOT NULL,
userPhoneNo VARCHAR(11) NOT NULL,
userDateJoined DATE NOT NULL,
userPassword VARCHAR(40) NOT NULL,
PRIMARY KEY (userID)
)
ENGINE = INNODB,
AUTO_INCREMENT = 19,
AVG_ROW_LENGTH = 8192,
CHARACTER SET latin1,
COLLATE latin1_swedish_ci;
--
-- Create index `userEmail_Unique` on table `tblusers`
--
ALTER TABLE tblusers
ADD UNIQUE INDEX userEmail_Unique(userEmail);
--
-- Create index `UserName_Unique` on table `tblusers`
--
ALTER TABLE tblusers
ADD UNIQUE INDEX UserName_Unique(userName);
--
-- Create table `tblrelationships`
--
CREATE TABLE IF NOT EXISTS tblrelationships (
relID INT(11) NOT NULL AUTO_INCREMENT,
relPatientID INT(11) NOT NULL,
relCarerID INT(11) DEFAULT NULL,
relStartDate DATE DEFAULT NULL,
relEndDate DATE DEFAULT NULL,
relJoinNUm VARCHAR(10) NOT NULL,
relJoinNumDate DATE NOT NULL,
PRIMARY KEY (relID)
)
ENGINE = INNODB,
CHARACTER SET latin1,
COLLATE latin1_swedish_ci;
--
-- Create index `relCarerID` on table `tblrelationships`
--
ALTER TABLE tblrelationships
ADD INDEX relCarerID(relCarerID);
--
-- Create index `relPatientID` on table `tblrelationships`
--
ALTER TABLE tblrelationships
ADD INDEX relPatientID(relPatientID);
--
-- Create index `relRandNum_Unique` on table `tblrelationships`
--
ALTER TABLE tblrelationships
ADD UNIQUE INDEX relRandNum_Unique(relJoinNUm);
--
-- Create table `tbleventtype`
--
CREATE TABLE IF NOT EXISTS tbleventtype (
eventTypeID INT(11) NOT NULL AUTO_INCREMENT,
eventDesc VARCHAR(255) NOT NULL,
PRIMARY KEY (eventTypeID)
)
ENGINE = INNODB,
AUTO_INCREMENT = 4,
AVG_ROW_LENGTH = 8192,
CHARACTER SET latin1,
COLLATE latin1_swedish_ci;
--
-- Create table `tblevents`
--
CREATE TABLE IF NOT EXISTS tblevents (
eventID INT(11) NOT NULL AUTO_INCREMENT,
eventType INT(11) NOT NULL DEFAULT 1,
eventStartDate DATE NOT NULL,
eventTimeReport VARCHAR(8) NOT NULL DEFAULT '00:00:00',
eventAcknowledged DATETIME DEFAULT NULL,
eventReminderDElay DOUBLE NOT NULL DEFAULT 10,
eventOverdueActionToTake INT(11) NOT NULL DEFAULT 2,
eventOverdueLengthLive INT(11) NOT NULL DEFAULT 30,
eventDescription VARCHAR(1024) NOT NULL,
eventImg VARCHAR(255) DEFAULT NULL,
eventRepeat TINYINT(1) NOT NULL DEFAULT 1,
eventTimes VARCHAR(255) DEFAULT NULL,
eventRepeatFrequency INT(11) DEFAULT NULL,
eventStopDate DATE DEFAULT NULL,
eventKeepLength INT(11) NOT NULL DEFAULT 14,
eventPatientID INT(11) NOT NULL,
eventDescShort VARCHAR(45) NOT NULL,
PRIMARY KEY (eventID)
)
ENGINE = INNODB,
AUTO_INCREMENT = 10,
AVG_ROW_LENGTH = 4096,
CHARACTER SET latin1,
COLLATE latin1_swedish_ci;
--
-- Create index `eventOverdueActionToTake` on table `tblevents`
--
ALTER TABLE tblevents
ADD INDEX eventOverdueActionToTake(eventOverdueActionToTake);
--
-- Create index `eventPatientID` on table `tblevents`
--
ALTER TABLE tblevents
ADD INDEX eventPatientID(eventPatientID);
--
-- Create index `eventType` on table `tblevents`
--
ALTER TABLE tblevents
ADD INDEX eventType(eventType);
--
-- Create table `tbleventlog`
--
CREATE TABLE IF NOT EXISTS tbleventlog (
ID INT(11) NOT NULL AUTO_INCREMENT,
UserID INT(11) NOT NULL,
Description VARCHAR(255) NOT NULL,
DateTime VARCHAR(255) NOT NULL,
Acknowledged TINYINT(1) NOT NULL DEFAULT 0,
KeepLength INT(11) NOT NULL,
DateAdded DATE NOT NULL,
PRIMARY KEY (ID)
)
ENGINE = INNODB,
AUTO_INCREMENT = 2,
CHARACTER SET utf8,
COLLATE utf8_unicode_ci;
--
-- Create table `tblevenoverdueactions`
--
CREATE TABLE IF NOT EXISTS tblevenoverdueactions (
eventOverdueActionID INT(11) NOT NULL AUTO_INCREMENT,
eventOverdueAction VARCHAR(255) NOT NULL,
PRIMARY KEY (eventOverdueActionID)
)
ENGINE = INNODB,
AUTO_INCREMENT = 3,
AVG_ROW_LENGTH = 8192,
CHARACTER SET latin1,
COLLATE latin1_swedish_ci;
--
-- Restore previous SQL mode
--
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
--
-- Enable foreign keys
--
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; |
DROP TABLE IF EXISTS orders;
CREATE TABLE `orders` (
id INT AUTO_INCREMENT PRIMARY KEY,
`client_id` int DEFAULT NULL,
`quantity` int NOT NULL,
`created_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ;
INSERT INTO `orders` (`id`, `client_id`, `quantity`, `created_date`) VALUES
(1, 1, 1, '2021-05-23 21:33:05'),
(2, 2, 1, '2021-05-23 21:33:50'),
(3, 3, 1, '2021-05-23 21:33:50'),
(4, 4, 1, '2021-05-23 21:33:50'),
(5, 5, 1, '2021-05-23 21:33:50'),
(6, 6, 1, '2021-05-23 21:33:50'),
(7, 7, 1, '2021-05-23 21:33:50'),
(8, 8, 1, '2021-05-23 21:33:50'),
(9, 9, 1, '2021-05-23 21:33:50'),
(10, 10, 1, '2021-05-23 21:33:50'); |
-- TITLE1:
-- TITLE2: Displaying Information About Transactions Received and Applied
-- DESC:
COLUMN APPLY_NAME HEADING 'Apply Process Name' FORMAT A20
COLUMN TOTAL_RECEIVED HEADING 'Total|Trans|Received' FORMAT 99999999
COLUMN TOTAL_APPLIED HEADING 'Total|Trans|Applied' FORMAT 99999999
COLUMN TOTAL_ERRORS HEADING 'Total|Apply|Errors' FORMAT 9999
COLUMN BEING_APPLIED HEADING 'Total|Trans Being|Applied' FORMAT 99999999
COLUMN UNASSIGNED_COMPLETE_TXNS HEADING 'Total|Unnasigned|Trans' FORMAT 99999999
COLUMN TOTAL_IGNORED HEADING 'Total|Trans|Ignored' FORMAT 99999999
SELECT APPLY_NAME,
TOTAL_RECEIVED,
TOTAL_APPLIED,
TOTAL_ERRORS,
(TOTAL_ASSIGNED - (TOTAL_ROLLBACKS + TOTAL_APPLIED)) BEING_APPLIED,
UNASSIGNED_COMPLETE_TXNS,
TOTAL_IGNORED
FROM V$STREAMS_APPLY_COORDINATOR;
|
DELETE FROM Feedbacks
WHERE CustomerId=14 OR
ProductId=5 |
-- ouvrir la console SQL sous XAMPP :
cd c:\xampp\mysql\bin
mysql.exe -u root --password
-- Ligne de commentaire en SQL débute par --
-- Les requêtes ne sont pas sensibles à la casse mais une convention indique qu'il faut mettre les mots clés des requêtes en MAJUSCULES.
--********************************
-- Requêtes générales
-- ***************************
CREATE DATABASE entreprise; -- crée une nouvelle base de données appelée "entreprise"
SHOW DATABASES; -- permet d'afficher les BDD disponibles
-- NE PAS SAISIR DANS LA CONSOLE :
DROP DATABASE entreprise; -- supprimer base de données entreprise avec tout son contenu
DROP table employes; -- supprimer la table employes
TRUNCATE employes; -- vider la table employes de son contenu
-- On peut coller dans la console:
USE entreprise; -- se connecter à la BDD entreprise
SHOW TABLES; -- permet de lister les tables de la BDD en cours d'utilisation
DESC employes; -- observer la structure de la table ainsi que les champs (DESC pour describe)
--***************************
-- Requêtes de sélection
--***************************
SELECT nom, prenom FROM employes; -- affiche (sélectionne) le nom et le prénom de la table employes : SELECT sélectionne les champs indiqués, FROM la ou les tables utilisées
SELECT service FROM employes; -- affiche les services de l'entreprise
-- DISTINCT
-- On a vu dans la requête précédente que les services sont affichés plusieurs fois. pour éliminer les doublons, on utilise DISTINCT :
SELECT DISTINCT service from employes;
-- ALL ou *
-- On peut afficher toutes les informations issues d'une table avec une "*" (pour dire ALL) :
SELECT * FROM employes;
-- clause WHERE
SELECT prenom, nom FROM employes WHERE service = 'informatique'; -- affiche les noms et prénoms des employés du service informatique. Notez que le nom des champs ou des tables ne prennent pas de quotes, alors que les valeurs telle que 'informatique' prennent des quotes ou des guillemets. Cependant, s'il s'agit d'un chiffre, on ne lui met pas de quote.
-- BETWEEN
SELECT nom, prenom, date_embauche FROM employes WHERE date_embauche BETWEEN '2006-01-01' AND '2010-12-31'; -- affiche les employes dont la date d' embauche est entre 2006 et 2010
-- LIKE
SELECT prenom FROM employes WHERE prenom LIKE 's%'; -- affiche les prénoms des employés commençant par s. Le signe % est un joker qui remplace les autres caractères.
SELECT prenom FROM employes WHERE prenom LIKE '%-%'; -- affiche les prénoms qui contiennent un tiret. LIKE est utilisé entre autres pour les formulaires de recherche sur les sites.
-- Opérateurs de comparaison :
SELECT prenom, nom FROM employes WHERE service != 'informatique'; -- affiche les prenom et nom des employes n'étant pas du service informatique. != ou <>
-- =
-- <
-- >
-- <=
-- >=
-- != ou encore <> pour différent de
-- ORDER BY pour faire des tris :
SELECT nom, prenom, service, salaire FROM employes ORDER BY salaire; -- affiche les employes par salaire en ordre croissant par défaut.
SELECT nom, prenom, service, salaire FROM employes ORDER BY salaire ASC, prenom DESC; -- ASC pour un tri ascendant, DESC pour un tri descendant. Ici on trie les salaires par ordre croissant puis à salaire identique les prénoms par ordre décroissant.
-- LIMIT
SELECT nom, prenom, salaire FROM employes ORDER BY salaire DESC LIMIT 0,1; -- affiche l'employé ayant le salaire le plus élevé : on trie d'abord les salaires par ordre décroissant ( pour avoir le plus élevé en premier), puis on limite le résultat au premier enregistrement avec LIMIT 0,1. Le 0 signifie le point de départ de LIMIT, et le 1 signifie prendre 1 enregistrment. On utilise LIMIT dans la pagination sur les sites.
-- L'alias avec AS :
SELECT nom, prenom, salaire *12 AS salaire_annuel FROM employes; -- affiche le salaire sur 12 mois des employes. salaire_annuel est un alias qui "stocke" la valeur de ce qui précède
-- SUM
SELECT SUM(salaire * 12) FROM employes; -- affiche le salaire total annuel de tous les employés. SUM permet d'additionner des valeurs de champs différents
-- MIN et MAX :
SELECT MIN(salaire) FROM employes; -- Affiche le salaire le plus bas
SELECT MAX(salaire) FROM employes; -- Affiche le salaire le plus haut
SELECT prenom, MIN(salaire) FROM employes; -- ne donne pas le résultat attendu, car affiche le premier nom rencontré dans la table (Jean-pierre). Il faut pour répondre à cette question utiliser ORDER BY et LIMIT comme au dessus.
SELECT prenom, salaire FROM employes ORDER BY salaire ASC LIMIT 0,1;
-- AVG (average)
SELECT AVG(salaire) FROM employes; -- affiche le salaire moyen dans l'entreprise
-- ROUND
SELECT ROUND(AVG(salaire), 1) FROM employes; --affiche le salaire moyen arrondi à 1 chiffre près apres la virgule.
-- COUNT
SELECT COUNT(id_employes) FROM employes WHERE sexe='f'; -- affiche le nombre d'employé féminins
-- IN
SELECT prenom, service FROM employes WHERE service IN ('comptabilite', 'informatique'); -- affiche les employes appartenant à la comptabilite et l'informatique'
-- NOT IN
SELECT prenom, service FROM employes WHERE service NOT IN ('comptabilite', 'informatique'); -- affiche les employes n' appartenant pas à la comptabilite et l'informatique'
-- AND et OR
SELECT prenom, service, salaire FROM employes WHERE service = 'commercial' AND salaire <= 2000; -- affiche les commerciaux dont le salaire est inférieur ou égal à 2000
SELECT prenom, service, salaire FROM employes WHERE (service = 'production' AND salaire =1900) OR salaire = 2300; -- affiche les employés du service production dont le salaire est de 1900, ou dans les autres services ceux qui gagnent 2300
-- GROUP BY
SELECT service, COUNT(id_employes) AS nombre FROM employes GROUP BY service; -- affiche le nombre d'employés par service. GROUP BY distribue les résultats du comptage par les services correspondants.
-- GROUP BY ... HAVING
SELECT service, COUNT(id_employes) AS nombre FROM employes GROUP BY service HAVING nombre > 1; -- affiche les services où il y'a plus d'un employé. HAVING remplace WHERE dans un GROUP BY.
--**************************************
-- Requêtes d'insertion
--**************************************
SELECT * FROM employes; -- on observe la table avant modification
INSERT INTO employes (id_employes, prenom, nom, sexe, service, date_embauche, salaire) VALUES (8059, 'alexis', 'richy', 'm', 'informatique', '2011-12-28', 1800); -- insertion d'un employé. Notez que l'ordre des champs énoncés entre les 2 paires de parenthèses doit être le même pour que les valeurs correspondent.
-- Une requête sans préciser les champs concernés
INSERT INTO employes VALUES (8060, 'test', 'test', 'm', 'test', '2012-12-28', 1800, 'valeur en trop'); -- insertion d'un employé sans préciser la liste des champs si et seulement si le nombre et l'ordre des valeurs attendues sont respectées => ici erreur car il y'a une valeur en trop !
--**************************************
-- Requêtes de modification
--**************************************
-- UPDATE
UPDATE employes SET salaire = 1870 WHERE nom = 'cottet'; -- je modifie le salaire de l'employé de nom Cottet
UPDATE employes SET salaire = 1871 WHERE id_employes = 699; -- il est recommandé de faire les modifications de données par les id car ils sont uniques. Cela évite d'updater plusieurs enregistrements à la fois.
UPDATE employes SET salaire = 1872, service = "autre" WHERE id_employes = 699; -- on modifie 2 valeurs dans la même requête
-- A ne pas faire (sauf cas contraire) : un UPDATE sans clause WHERE :
UPDATE employes SET salaire = 1870; -- ici les salaires de tous les employés passent à 1870
-- REPLACE
REPLACE INTO employes (id_employes, prenom, nom, sexe, service, date_embauche, salaire) VALUES (2000, 'test', 'test', 'm', 'marketing', '2010-07-05', 2600);
-- l'id employes 2000 n'existant pas; REPLACE se comporte comme un INSERT
REPLACE INTO employes (id_employes, prenom, nom, sexe, service, date_embauche, salaire) VALUES (2000, 'test2', 'test2', 'm', 'marketing', '2010-07-05', 2601);
-- comme l'id_employes existe, REPLACE se comporte comme un UPDATE
--**************************************
-- Requêtes de suppression
--**************************************
-- DELETE
DELETE FROM employes WHERE id_employes = 900; -- suppression de l'employé dont l'id est 900
DELETE FROM employes WHERE service = 'informatique' AND id_employes != 802; -- supprrime tous les informaticiens sauf un(dont l'id est 802)
DELETE FROM employes WHERE id_employes = 388 OR id_employes = 990; -- supprime 2 employes qui n'ont pas de points communs. Il s'agit d'un OR et non pas d'un AND car un employé ne peut pas avoir 2 id différents
-- A ne pas faire : un DELETE sans clause WHERE
DELETE FROM employes; -- revient à faire un TRUNCATE de table qui est irréversible
--**************************************
-- Exercices
--**************************************
--1. Afficher les service de l'employe 547
SELECT service FROM employes WHERE id_employes = 547;
--2. Afficher la date d embauche d'Amandine
SELECT date_embauche FROM employes WHERE prenom = 'Amandine';
--3. Afficher le nombre de commerciaux
SELECT COUNT(id_employes) FROM employes WHERE service = 'commercial';
--4. Afficher le coût des commerciaux par service
SELECT SUM(salaire * 12) FROM employes WHERE service = 'commercial';
--5. Afficher le salaire moyen par service
SELECT AVG(salaire), service FROM employes GROUP BY service;
--6. Afficher le nombre de recrutements sur l'année 2010 ( 3 syntaxes possibles)
SELECT COUNT(id_employes) FROM employes WHERE date_embauche BETWEEN '2010-01-01' AND '2010-12-31';
SELECT COUNT(id_employes) FROM employes WHERE date_embauche >= '2010-01-01' AND date_embauche <= '2010-12-31';
SELECT COUNT(date_embauche) FROM employes WHERE date_embauche LIKE '2010%';
--7. Augmenter le salaire de chaque employé de 100
UPDATE employes SET salaire = salaire + 100;
--8. Afficher le nombre de services différents
SELECT COUNT(DISTINCT service) FROM employes;
--9. Afficher le nombre d'employés par service
SELECT service, COUNT(id_employes) FROM employes GROUP BY service;
--10. Afficher les infos de l'employé du service commercial ayant le salaire le plus élevé
SELECT nom, prenom, salaire FROM employes WHERE service = 'commercial' ORDER BY salaire DESC LIMIT 0,1;
--11. Afficher l'employé ayant été embauché en dernier
SELECT id_employes, nom, prenom, date_embauche FROM employes ORDER BY date_embauche DESC LIMIT 0,1;
|
-- More deltas for Loop logic
-- omitted the 'use' statement, so we can source this in both loop_logic and autoapp_test
-- use loop_logic;
alter table loop_summary modify `bolus_value` double;
alter table loop_summary modify `carb_value` double;
-- Also, all the integer fields are storing just 0/1. So we should make them tinyint.
|
SELECT *
FROM CITY
WHERE COUNTRYCODE = 'JPN'; |
set search_path = pictures;
insert into people values (1, 'Claude', 'Monet', '1840-11-14');
insert into people values (2, 'Tiziano', 'Vecelli');
insert into people values (3, 'Jean-Honore', 'Fragonard', '1732-04-05');
insert into people values (4, 'Georges', 'Seurat', '1859-12-02');
insert into people values (5, 'Pablo', 'Picasso', '1881-10-25');
insert into people values (6, 'William', 'Turner', '1775-04-23');
insert into people values (7, 'Henri', 'Matisse', '1869-12-31');
insert into people values (8, 'Gustav', 'Klimt', '1862-06-14');
insert into people values (9, 'David', 'Hockney', '1937-06-09');
insert into people values (10, 'Louisine', 'Havemeyer', '1855-06-28');
insert into people values (11, 'Richard', 'Seymour-Conway', '1800-02-22');
insert into people values (12, 'Helen', 'Bartlett');
insert into people values (13, 'Solomon', 'Guggenheim', '1861-02-02');
insert into museum values (1, 'Vetropolian museum of art', 'New York');
insert into museum values (2, 'Galleria degli Uffizi', 'Florence');
insert into museum values (3, 'Wallace Collection', 'London');
insert into museum values (4, 'Art Institute of Chicago', 'Chicago');
insert into museum values (5, 'Solomon R. Guggenheim Museum', 'New York');
insert into museum values (6, 'The National Gallery', 'London');
insert into museum values (7, 'Yale Center for British Art', 'New Haven');
insert into museum values (8, 'Musée National dArt Moderne', 'Paris');
insert into museum values (9, 'Osterreichische Galerie Belvedere', 'Viena');
insert into museum values (10, 'Museum of Art Lucerne', 'Lucerne');
insert into museum values (11, 'Centre Pompidou', 'Paris');
insert into picture values (1, 'Bridge over a Pond of Water Lilies', 1, 10, 1, '1899');
insert into picture values (2, 'Venus of Urbino', 2, null, 2, '1534');
insert into picture values (3, 'The Swing', 3, 11, 3, '1767');
insert into picture values (4, 'A Sunday Afternoon on the Island of La Grande Jatte', 4, 12, 4, '1886');
insert into picture values (5, 'The Accordionist', 5, 13, 5, '1911');
insert into picture values (6, 'Rain, Steam and Speed', 6, null, 6, '1844');
insert into picture values (7, 'Upper Fall of the Reichenbach: Rainbow', 6, null, 7, '1810');
insert into picture values (8, 'Perseus and Andromeda', 2, null, 2, '1534');
insert into picture values (9, 'La Blouse roumaine', 7, null, 8, '1940');
insert into picture values (10, 'The Kiss', 8, null, 9, '1908');
insert into picture values (11, 'Nichols Canyon', 9, 9, null, '1980');
insert into movement values (1, 'Impressionism');
insert into movement values (2, 'Renaissance');
insert into movement values (3, 'Rococo');
insert into movement values (4, 'Pointillism');
insert into movement values (5, 'Neo-impressionism');
insert into movement values (6, 'Cubism');
insert into movement values (7, 'Abstractionism');
insert into movement values (8, 'Romanticism');
insert into movement values (9, 'Modern');
insert into movement values (10, 'Pop art');
insert into movement_x_picture values (1, 1);
insert into movement_x_picture values (2, 2);
insert into movement_x_picture values (3, 3);
insert into movement_x_picture values (4, 4);
insert into movement_x_picture values (5, 4);
insert into movement_x_picture values (6, 5);
insert into movement_x_picture values (7, 5);
insert into movement_x_picture values (8, 6);
insert into movement_x_picture values (8, 7);
insert into movement_x_picture values (2, 8);
insert into movement_x_picture values (9, 9);
insert into movement_x_picture values (9, 10);
insert into movement_x_picture values (10, 11);
insert into exhibition values (1, 'Tititan: love, desire, death', 6, '2020-03-16', '2021-01-17');
insert into exhibition values (2, 'Lucerne through Turners eyes', 10, '2019-06-01', '2019-08-31');
insert into exhibition values (3, 'Matisse', 11, '2020-10-21', '2021-02-22');
insert into exhibition values(4, 'Salvador Dali & Pablo Picasso');
insert into exhibition_x_picture values (1, 2);
insert into exhibition_x_picture values (2, 6);
insert into exhibition_x_picture values (2, 7);
insert into exhibition_x_picture values (1, 8);
insert into exhibition_x_picture values (3, 9);
|
DROP TABLE `p2o40rwbj6zuxy26`.`users_groups`;
DROP TABLE `p2o40rwbj6zuxy26`.`users`;
DROP TABLE `p2o40rwbj6zuxy26`.`groups`;
use p2o40rwbj6zuxy26;
CREATE TABLE `p2o40rwbj6zuxy26`.`users` (
`u_id` INT NOT NULL AUTO_INCREMENT,
`full_name` VARCHAR(99) NOT NULL,
`address` VARCHAR(45) DEFAULT NULL,
`email` VARCHAR(45) NOT NULL,
`password` varchar(45) NOT NULL,
`wishes` varchar(500) DEFAULT NULL,
`createdAt` DATETIME DEFAULT CURRENT_TIMESTAMP,
`updatedAt` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`u_id`),
UNIQUE KEY `email_UNIQUE` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `p2o40rwbj6zuxy26`.`groups` (
`g_id` int(11) NOT NULL AUTO_INCREMENT,
`group_name` varchar(45) NOT NULL,
`dollar_amount` int(11) NOT NULL,
`active` tinyint(4) NOT NULL DEFAULT '1',
`createdAt` datetime DEFAULT CURRENT_TIMESTAMP,
`updatedAt` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`g_id`),
UNIQUE KEY `group_name_UNIQUE` (`group_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `p2o40rwbj6zuxy26`.`users_groups` (
`id` INT NOT NULL AUTO_INCREMENT,
`users_id` INT NOT NULL,
`groups_id` INT NOT NULL,
`admin` TINYINT NOT NULL DEFAULT 0,
`item_note` VARCHAR(200),
`assigned_user_id` INT NOT NULL DEFAULT 0,
`createdAt` DATETIME DEFAULT CURRENT_TIMESTAMP,
`updatedAt` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
FOREIGN KEY (`users_id`) REFERENCES users(`u_id`),
FOREIGN KEY (`groups_id`) REFERENCES groups(`g_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Author: luanm
* Created: 01/03/2018
*/
DROP DATABASE biblioteca;
CREATE DATABASE IF NOT EXISTS biblioteca;
USE biblioteca;
CREATE TABLE IF NOT EXISTS pessoas(
id INT PRIMARY KEY AUTO_INCREMENT,
nome VARCHAR(128),
cpf VARCHAR(12),
rua VARCHAR(128),
bairro VARCHAR(64),
email VARCHAR(64),
telefone VARCHAR(12),
id_funcionario INT NULL,
id_leitor INT NULL
);
CREATE TABLE IF NOT EXISTS leitores(
id INT PRIMARY KEY AUTO_INCREMENT,
quantidade_livros INT NULL DEFAULT 0,
bloqueio BOOLEAN NULL DEFAULT FALSE,
id_pessoa INT NULL
);
CREATE TABLE IF NOT EXISTS funcionarios(
id INT PRIMARY KEY AUTO_INCREMENT,
usuario VARCHAR(32) NOT NULL,
senha VARCHAR(32) NOT NULL,
id_pessoa INT NULL
);
CREATE TABLE IF NOT EXISTS livros(
id INT PRIMARY KEY AUTO_INCREMENT,
titulo VARCHAR(128),
autor VARCHAR(64),
categoria VARCHAR(32),
status VARCHAR(32),
ano INT,
isbn INT,
edicao INT,
id_emprestimo INT NULL
);
CREATE TABLE IF NOT EXISTS emprestimos(
id INT PRIMARY KEY AUTO_INCREMENT,
id_funcionario INT NULL,
id_leitor INT NULL,
data_emprestimo DATE,
data_devolucao DATE
);
CREATE TABLE IF NOT EXISTS reservas(
id INT PRIMARY KEY AUTO_INCREMENT,
id_funcionario INT NULL,
id_leitor INT NULL,
id_livro INT NULL,
data_reserva DATE
);
CREATE TABLE IF NOT EXISTS livrosreservados(
id INT PRIMARY KEY AUTO_INCREMENT,
id_livro INT NULL,
id_reserva INT NULL
);
-- Atribuindo relacionamento (Chaves estrangeiras)
ALTER TABLE pessoas
ADD CONSTRAINT fk_pessoa_funcionario
FOREIGN KEY(id_funcionario) REFERENCES funcionarios(id) ON DELETE CASCADE,
ADD CONSTRAINT fk_pessoa_leitor
FOREIGN KEY(id_leitor) REFERENCES leitores(id) ON DELETE CASCADE;
ALTER TABLE funcionarios ADD CONSTRAINT fk_funcionario_pessoa
FOREIGN KEY(id_pessoa) REFERENCES pessoas(id) ON DELETE CASCADE;
ALTER TABLE leitores ADD CONSTRAINT fk_leitor_pessoa
FOREIGN KEY(id_pessoa) REFERENCES pessoas(id) ON DELETE CASCADE;
ALTER TABLE livros
ADD CONSTRAINT fk_livro_emprestimo
FOREIGN KEY(id_emprestimo) REFERENCES emprestimos(id) ON DELETE SET NULL;
ALTER TABLE emprestimos
ADD CONSTRAINT fk_emprestimo_funcionario
FOREIGN KEY(id_funcionario) REFERENCES pessoas(id) ON DELETE SET NULL,
ADD CONSTRAINT fk_emprestimo_leitor
FOREIGN KEY(id_leitor) REFERENCES pessoas(id) ON DELETE SET NULL;
ALTER TABLE reservas
ADD CONSTRAINT fk_reserva_funcionario
FOREIGN KEY(id_funcionario) REFERENCES pessoas(id) ON DELETE SET NULL,
ADD CONSTRAINT fk_reserva_leitor
FOREIGN KEY(id_leitor) REFERENCES pessoas(id) ON DELETE SET NULL,
ADD CONSTRAINT fk_reserva_livro
FOREIGN KEY(id_livro) REFERENCES livros(id) ON DELETE SET NULL;
INSERT INTO pessoas (nome, cpf, rua, bairro, email, telefone) VALUES
("Pessoa1", "1234", "rua 1", "bairro 1", "pessoa@gmail.com", "999999");
INSERT INTO leitores (quantidade_livros, bloqueio, id_pessoa) VALUES
(0, false, 1);
UPDATE pessoas SET id_leitor = 1 WHERE id = 1;
INSERT INTO pessoas (nome, cpf, rua, bairro, email, telefone) VALUES
("funcionario", "555", "Alfeneiiros 1", "centro", "caraca@gmail.com", "2222");
INSERT INTO funcionarios (usuario, senha, id_pessoa) VALUES
("func", "123", 2);
UPDATE pessoas SET id_funcionario = 1 WHERE id = 2;
|
-- access postgres:
-- psql -U postgres url_shortener
-- CREATE DATABASE url_shortener;
-- CREATE TABLE url_table(
-- originalurl text primary key,
-- shorturl text unique not null
-- );
-- insert into url_table(originalurl, shorturl) values('https://www.youtube.com/', 'http:localhost:3001/JWx2WinDy0e6Vvwr5dqEk'); |
-- Jun 1, 2009 4:30:09 PM MYT
-- RMA Feature - ID: 1756793
UPDATE AD_Val_Rule SET Code='C_DocType.DocBaseType IN (''SOO'', ''POO'') AND C_DocType.IsSOTrx=''@IsSOTrx@'' AND COALESCE(C_DocType.DocSubTypeSO,'' '')<>''RM''',Updated=TO_TIMESTAMP('2009-06-01 16:30:09','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Val_Rule_ID=133
;
COMMIT;
|
USE `redm_extended`;
INSERT INTO `items` (`name`, `label`, `weight`, `rare`, `can_remove`) VALUES
('blueberry', 'BlueBerries', 1, 0, 1),
('stick', 'Stick', 1, 0, 1)
;
|
CREATE DATABASE drinksDB;
USE drinksDB;
CREATE TABLE drinks (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
source VARCHAR(100) NOT NULL,
ingredients TEXT,
recipe TEXT NOT NULL,
blurb TEXT NOT NULL,
imageURL STRING NOT NULL,
createdAt TIMESTAMP NOT NULL default CURRENT_TIMESTAMP,
updatedAt TIMESTAMP NOT NULL,
PRIMARY KEY(id)
);
CREATE TABLE foods (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
source VARCHAR(100) NOT NULL,
ingredients TEXT,
recipe TEXT NOT NULL,
blurb TEXT NOT NULL,
imageURL STRING NOT NULL,
createdAt TIMESTAMP NOT NULL default CURRENT_TIMESTAMP,
updatedAt TIMESTAMP NOT NULL,
PRIMARY KEY(id)
);
|
drop table IF EXISTS orders;
drop table IF EXISTS equipments;
drop table IF EXISTS orderEquipment;
drop table IF EXISTS tickets;
drop table IF EXISTS orderTicket;
drop table IF EXISTS orderInsurance;
drop table IF EXISTS costs;
drop table IF EXISTS contacts;
drop table IF EXISTS orderNotes;
drop table IF EXISTS orderCompleted;
drop table IF EXISTS groups;
drop table IF EXISTS betausers;
create table betausers (
uid char[20] primary key,
email text
);
create table orders (
o_id char[20] primary key,
departDate char not null,
returnDate char not null,
campingPeople char[2] not null,
isDiy char[1] not null
);
create table orderNotes (
o_id char[20],
note text
);
create table costs (
o_id char[20] not null,
equipmentTotal integer,
ticketTotal integer,
insurance integer,
allTotal integer
);
create table contacts (
o_id char[20],
name text,
tel text,
email text,
note text
);
create table equipments (
e_id char[2] primary key,
name char not null,
price integer not null,
chinese_name char
);
create table orderEquipment (
o_id char[20] not null,
e_id char[2] not null,
quantity char[2],
cost integer
);
create table tickets (
t_id char[2] primary key,
name char not null,
price integer not null,
chinese_name char
);
create table orderTicket (
o_id char[20] not null,
t_id char[2] not null,
quantity char[2],
cost integer
);
create table orderInsurance (
o_id char[20] not null,
quantity char[2],
cost integer
);
create table orderCompleted (
o_id char[20] not null,
c char[1]
);
create table groups (
o_id char[20] not null,
name text,
tel text,
email text,
note text
);
insert into equipments values(12,'tent2',40,'双人帐篷');
insert into equipments values(14,'tent4',60,'四人帐篷');
insert into equipments values(18,'tent8',100,'八人帐篷');
insert into equipments values(20,'pad',10,'防潮垫');
insert into equipments values(30,'sleepingbag',10,'睡袋');
insert into equipments values(40,'light',5,'帐篷灯');
insert into equipments values(50,'backbag',30,'登山包');
insert into equipments values(90,'combo',25,'露营套餐');
insert into tickets values(01,'la',30,'临安(烧烤)');
insert into tickets values(02,'qdh',50,'千岛湖(烧烤+篝火)');
insert into tickets values(03,'gqd',70,'枸杞岛(船票+烧烤)');
insert into tickets values(04,'nzj',50,'鸟之家(烧烤+篝火)');
insert into tickets values(00,'self',0,'自定地点');
|
Create Procedure Sp_Get_TaxSuff_Details(@Product_Code as nvarchar(30))
as
Select Percentage, LSTApplicableON , LSTPartOff , CSTApplicableON , CSTPartOff
From items, Tax
Where Product_Code = @Product_Code And Tax.Tax_Code = Items.TaxSuffered
|
USE CBSS;
DROP TABLE IF EXISTS `News`;
CREATE TABLE `News` (
`NewsID` INT NOT NULL AUTO_INCREMENT,
`BankID` INT NOT NULL ,
`BranchID` INT NOT NULL ,
`NewsTitle` VARCHAR(50) NOT NULL,
`ThumbnailUrl` VARCHAR(200) NOT NULL,
`NewsDate` DATETIME NOT NULL,
`Status` CHAR(1) NOT NULL DEFAULT 'A',
`InUser` VARCHAR(15) NOT NULL DEFAULT 'sys',
`InDate` TIMESTAMP NOT NULL DEFAULT current_timestamp,
`LastEditUser` VARCHAR(15) NOT NULL DEFAULT 'sys',
`LastEditDate` TIMESTAMP NOT NULL DEFAULT current_timestamp ON UPDATE current_timestamp,
PRIMARY KEY (`NewsID`)
) ENGINE = INNODB DEFAULT CHAR SET = UTF8;
CREATE INDEX News_Index_BankID ON `News`(`BankID`);
CREATE INDEX News_Index_BranchID ON `News`(`BranchID`); |
DROP TABLE coordinate;
DROP TABLE ship;
DROP TABLE board;
CREATE TABLE board
(name varchar(25) NOT NULL,
isturn boolean);
CREATE TABLE ship
(name varchar(25) NOT NULL,
issunk boolean,
boardname varchar(25) NOT NULL);
CREATE TABLE coordinate
(xcoord numeric(1) NOT NULL,
ycoord numeric(1) NOT NULL,
boardname varchar(25) NOT NULL,
shipname varchar(25),
selected boolean,
hit boolean);
ALTER TABLE board
add constraint board_name_pk primary key(name);
ALTER TABLE ship
add constraint ship_name_boardname_pk primary key(name, boardname);
ALTER TABLE coordinate
add constraint coordinate_xcord_ycord_boardname_pk primary key(xcoord,ycoord,boardname);
ALTER TABLE ship
add constraint ship_boardname_fk foreign key(boardname)
references board(name);
ALTER TABLE coordinate
add constraint coordinate_boardname_fk foreign key(boardname)
references board(name);
ALTER TABLE coordinate
add constraint coordinate_shipname_fk foreign key(shipname)
references ship(name); |
CREATE TABLE Percorre
(
numero_linha INTEGER,
numero_itinerario_percorrido INTEGER,
PRIMARY KEY(numero_linha, numero_itinerario_percorrido),
FOREIGN KEY(numero_linha) REFERENCES Linha(codigo_linha),
FOREIGN KEY(numero_itinerario_percorrido) REFERENCES Itinerario(codigo_itinerario)
); |
REM ------------------------------------------------------------------------
REM REQUIREMENTS:
REM SELECT on V$ tables
REM ------------------------------------------------------------------------
REM PURPOSE:
REM Show sga objects
REM ------------------------------------------------------------------------
set linesize 96
set pages 100
set feedback off
set verify off
col owner for a15 head Owner
col object_name for a30 head Name
col object_type for a10 trunc head Type
col bytes for 999,999,999
col percent for 999 head "% "
SELECT p1.value*p2.value data_cache_size
FROM v$parameter p1, v$parameter p2
WHERE p1.name='db_block_buffers'
AND p2.name='db_block_size'
;
prompt
break on report
compute sum of bytes on report
SELECT cache.obj, objs.owner, objs.object_name, objs.object_type,
(count(*) * 8192) bytes, (count(*) * 819200 / &&data_cache_size) percent
FROM sys.x$bh cache, dba_objects objs
WHERE objs.object_id = cache.obj
GROUP BY cache.obj, objs.owner, objs.object_name, objs.object_type
ORDER BY 3
;
prompt
exit
|
-- phpMyAdmin SQL Dump
-- version 4.1.14
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jan 23, 2017 at 08:42 PM
-- Server version: 5.6.17
-- PHP Version: 5.5.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `municipio_ps`
--
-- --------------------------------------------------------
--
-- Table structure for table `permiso`
--
CREATE TABLE IF NOT EXISTS `permiso` (
`permisoID` int(11) NOT NULL AUTO_INCREMENT,
`permisoEstado` tinyint(1) NOT NULL,
`tareaID` int(11) NOT NULL,
`rolID` int(11) NOT NULL,
PRIMARY KEY (`permisoID`),
KEY `tareaID` (`tareaID`),
KEY `rolID` (`rolID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `persona`
--
CREATE TABLE IF NOT EXISTS `persona` (
`personaID` int(11) NOT NULL AUTO_INCREMENT,
`personaDNI` char(8) NOT NULL,
`personaNombres` varchar(50) NOT NULL,
`personaApellidos` varchar(100) NOT NULL,
`personaDireccion` varchar(100) NOT NULL,
`personaFechaNacimiento` date NOT NULL,
`personaTelefono` char(9) NOT NULL,
PRIMARY KEY (`personaID`),
UNIQUE KEY `personaDNI` (`personaDNI`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `persona`
--
INSERT INTO `persona` (`personaID`, `personaDNI`, `personaNombres`, `personaApellidos`, `personaDireccion`, `personaFechaNacimiento`, `personaTelefono`) VALUES
(1, '12345678', 'Karla', 'Mendoza', 'Dirección', '2017-01-20', '949123456');
-- --------------------------------------------------------
--
-- Table structure for table `rol`
--
CREATE TABLE IF NOT EXISTS `rol` (
`rolID` int(11) NOT NULL AUTO_INCREMENT,
`rolDescripcion` varchar(50) NOT NULL,
`rolNombre` varchar(50) NOT NULL,
`rolEstado` tinyint(1) NOT NULL,
PRIMARY KEY (`rolID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `rol`
--
INSERT INTO `rol` (`rolID`, `rolDescripcion`, `rolNombre`, `rolEstado`) VALUES
(1, 'Presidente del Municipio del PS', 'Presidente', 1);
-- --------------------------------------------------------
--
-- Table structure for table `rol_usuario`
--
CREATE TABLE IF NOT EXISTS `rol_usuario` (
`rolusuarioID` int(11) NOT NULL AUTO_INCREMENT,
`rolusuarioEstado` tinyint(1) NOT NULL,
`personaID` int(11) NOT NULL,
`rolID` int(11) NOT NULL,
PRIMARY KEY (`rolusuarioID`),
KEY `rolID` (`rolID`),
KEY `personaID` (`personaID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `rol_usuario`
--
INSERT INTO `rol_usuario` (`rolusuarioID`, `rolusuarioEstado`, `personaID`, `rolID`) VALUES
(1, 1, 1, 1);
-- --------------------------------------------------------
--
-- Table structure for table `tarea`
--
CREATE TABLE IF NOT EXISTS `tarea` (
`tareaID` int(11) NOT NULL AUTO_INCREMENT,
`tareaNombre` varchar(50) NOT NULL,
`tareaDescripcion` varchar(50) NOT NULL,
`tareaIcono` varchar(50) NOT NULL,
`tareaOrden` int(11) NOT NULL,
`tareaURL` varchar(50) NOT NULL,
`tareaEstado` tinyint(1) NOT NULL,
PRIMARY KEY (`tareaID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `tarea`
--
INSERT INTO `tarea` (`tareaID`, `tareaNombre`, `tareaDescripcion`, `tareaIcono`, `tareaOrden`, `tareaURL`, `tareaEstado`) VALUES
(1, 'Administración', 'Administración del sistema', 'menu-icon fa fa-desktop', 1, '../Administracion/administracion_view.php', 1),
(2, 'Foro', 'Foro de alumnos', 'menu-icon fa fa-pencil-square-o', 2, '../Foro/foroadmin_view.php', 1),
(3, 'Actividades', 'Actividades municipales', 'menu-icon fa fa-calendar', 3, '../Actividades/actividades_view.php', 1),
(4, 'Noticias', 'Noticias municipales', 'menu-icon fa fa-list', 4, '../Noticias/noticias_view.php', 1);
-- --------------------------------------------------------
--
-- Table structure for table `usuario`
--
CREATE TABLE IF NOT EXISTS `usuario` (
`personaID` int(11) NOT NULL,
`usuarioLogin` varchar(50) NOT NULL,
`usuarioPassword` char(32) NOT NULL,
`extraordinario` boolean NOT NULL,
`usuarioEstado` boolean NOT NULL,
PRIMARY KEY (`personaID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `usuario`
--
INSERT INTO `usuario` (`personaID`, `usuarioLogin`, `usuarioPassword`, `usuarioEstado`) VALUES
(1, 'karlam123', '202cb962ac59075b964b07152d234b70', 1, 1);
--
-- Constraints for dumped tables
--
--
-- Constraints for table `permiso`
--
ALTER TABLE `permiso`
ADD CONSTRAINT `permiso_ibfk_1` FOREIGN KEY (`tareaID`) REFERENCES `tarea` (`tareaID`),
ADD CONSTRAINT `permiso_ibfk_2` FOREIGN KEY (`rolID`) REFERENCES `rol` (`rolID`);
--
-- Constraints for table `rol_usuario`
--
ALTER TABLE `rol_usuario`
ADD CONSTRAINT `rol_usuario_ibfk_1` FOREIGN KEY (`rolID`) REFERENCES `rol` (`rolID`),
ADD CONSTRAINT `rol_usuario_ibfk_2` FOREIGN KEY (`personaID`) REFERENCES `persona` (`personaID`);
--
-- Constraints for table `usuario`
--
ALTER TABLE `usuario`
ADD CONSTRAINT `usuario_ibfk_1` FOREIGN KEY (`personaID`) REFERENCES `persona` (`personaID`);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
DROP TABLE RESERVATED_ROOMS;
DROP TABLE RESERVATION;
DROP TABLE CONFIGURATION;
DROP TABLE ROOMS;
DROP TABLE HOTEL;
DROP TABLE CITY;
DROP TABLE COUNTRY;
DROP TYPE FOOD CASCADE;
DROP TYPE HOTEL_TYPE CASCADE; |
-- phpMyAdmin SQL Dump
-- version 4.0.4
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Dec 09, 2018 at 07:31 AM
-- Server version: 5.6.12-log
-- PHP Version: 5.4.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `medxol`
--
CREATE DATABASE IF NOT EXISTS `medxol` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `medxol`;
-- --------------------------------------------------------
--
-- Table structure for table `admin`
--
CREATE TABLE IF NOT EXISTS `admin` (
`AdminID` int(11) NOT NULL AUTO_INCREMENT,
`Email` varchar(50) NOT NULL,
`Password` varchar(50) NOT NULL,
PRIMARY KEY (`AdminID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `admin`
--
INSERT INTO `admin` (`AdminID`, `Email`, `Password`) VALUES
(1, 'info@medxol.com', '123');
-- --------------------------------------------------------
--
-- Table structure for table `services`
--
CREATE TABLE IF NOT EXISTS `services` (
`ServiceID` int(11) NOT NULL AUTO_INCREMENT,
`Date` varchar(20) DEFAULT NULL,
`Time` varchar(20) DEFAULT NULL,
`Service` varchar(40) DEFAULT NULL,
`SubCategory` varchar(50) NOT NULL,
`Charges` varchar(20) NOT NULL,
`UEmail` varchar(50) NOT NULL,
PRIMARY KEY (`ServiceID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
--
-- Dumping data for table `services`
--
INSERT INTO `services` (`ServiceID`, `Date`, `Time`, `Service`, `SubCategory`, `Charges`, `UEmail`) VALUES
(1, '12/12/2018', '00:13', 'HouseKeeping', '', '', ''),
(2, '12/11/2018', '11:11', 'Companionship', '', '', ''),
(3, '12/11/2018', '11:11', 'Personal Care & Medical L', '', '', 'mjam691@gmail.com'),
(4, '12/04/2018', '11:11', 'HouseKeeping', '', '', ''),
(5, '12/04/2018', '11:11', 'Meals & Transportation', '', '', 'mjam691@gmail.com'),
(6, '12/03/2018', '00:11', 'Personal Care & Medical Lab', 'Physyo Theraphy', '', 'mjam691@gmail.com'),
(7, '12/13/2018', '11:11', 'Personal Care & Medical Lab', 'Physyo Theraphy', '', 'mjam691@gmail.com'),
(8, '12/18/2018', '11:11', 'HouseKeeping', '', '', 'mjam691@gmail.com');
-- --------------------------------------------------------
--
-- Table structure for table `userinfo`
--
CREATE TABLE IF NOT EXISTS `userinfo` (
`UserID` int(11) NOT NULL AUTO_INCREMENT,
`CNIC` varchar(25) NOT NULL,
`Name` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`Password` varchar(50) NOT NULL,
`Age` int(10) NOT NULL,
`Number` varchar(25) NOT NULL,
`Gender` varchar(10) NOT NULL,
`Address` varchar(100) NOT NULL,
`City` varchar(50) NOT NULL,
`Landmark` varchar(25) NOT NULL,
PRIMARY KEY (`UserID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
--
-- Dumping data for table `userinfo`
--
INSERT INTO `userinfo` (`UserID`, `CNIC`, `Name`, `Email`, `Password`, `Age`, `Number`, `Gender`, `Address`, `City`, `Landmark`) VALUES
(3, '37405-0422983-0', 'Maryam Jamil', 'mjam691@gmail.com', '1234', 27, '3325568674', 'Female', 'House # 10, Opposite Peshawar Road', 'Rawalpindi', 'Chour Chowk'),
(4, '37415-0422983-0', 'Hasan', 'Hasan@medxol.com', '1234', 27, '3325568671', 'Male', 'House # 10, Opposite Peshawar Road', 'Rawalpindi', 'Saddar'),
(5, '37105-0422983-0', 'Ali Iqbal Bhatti', 'iqbal@medxol.com', '12345', 23, '3325568623', 'Male', 'House # 10, Opposite Peshawar Road', 'Rawalpindi', 'Saddar');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
SET NAMES UTF8;
USE coffee;
CREATE TABLE product(
pid INT PRIMARY KEY AUTO_INCREMENT,
pname VARCHAR(32),
ptitle VARCHAR(64),
pinfo VARCHAR(128),
pOrigin VARCHAR(16),
pwork VARCHAR(16),
ptasty VARCHAR(64),
pacidity VARCHAR(16),
palcohol VARCHAR(16),
pmfood VARCHAR(64),
plike VARCHAR(32),
price INT,
img VARCHAR(128),
bmimg VARCHAR(64)
);
INSERT INTO product VALUES(NULL,'凤舞祥云综合','均衡的风味带有草本和可可粉的香味',
'这款与众不同的综合咖啡是首款采用中国云南保山地区的咖啡豆和其他来自亚洲、太平洋地区的咖啡混合制成的综合咖啡豆。'
,'亚洲/太平洋','水洗法/半水洗法','温和清爽的酸度,中等醇度,均衡的风味并带有草本和可可粉的香味','较低',
'中等','奶油芝士类食品,太妃、枫糖和坚果类食品','低因祥龙综合咖啡®',299,'images/p13.jpg','images/lp13.jpg');
INSERT INTO product VALUES(NULL,'哥伦比亚',
'果仁味,可可味',
'醇度适中,口感顺滑平和,喝下去满口丰盈,并留下清脆而带有坚果的回味。'
,'拉丁美洲','水洗法','果仁味,可可味',
'中等','中等','胡桃,山核桃,焦糖','首选咖啡、危地马拉安提瓜咖啡',399,'images/p2.jpg','images/lp2.jpg'
);
INSERT INTO product VALUES(NULL,'综合咖啡豆',
'清爽,且极为平和',
'首选咖啡是一款中等醇度的拉丁美洲综合咖啡,其特点是具有活泼的酸度,以及清爽且极为平和的风味。'
,'拉丁美洲','水洗法','清爽,且极为平和',
'中等','中等','果仁,苹果,蓝莓','危地马拉安提瓜咖啡',399,'images/p6.jpg','images/lp6.jpg'
);
INSERT INTO product VALUES(NULL,'派克市场®烘焙',
'可可味,烘烤果仁味',
'中等醇度并伴随着可可和烤果仁的微妙风味,呈现出一杯令人愉悦而口感平衡的咖啡。'
,'拉丁美洲','水洗法','可可味,烘烤果仁味',
'中等','中等','巧克力,肉桂,果仁','首选咖啡、危地马拉安提瓜咖啡',399,'images/p10.jpg','images/lp10.jpg'
);
INSERT INTO product VALUES(NULL,'肯亚',
'葡萄柚味,浆果味',
'肯亚咖啡拥有多层次复杂的风味,包含果汁般的酸度、明显的葡萄柚味和葡萄酒的醇香,醇度中等。'
,'非洲/阿拉伯','水洗法','葡萄柚味,浆果味',
'较高','中等','葡萄柚,浆果,无核葡萄干,葡萄干','埃塞俄比亚斯丹摩咖啡',399,'images/p8.jpg','images/lp8.jpg'
);
INSERT INTO product VALUES(NULL,'危地马拉安提瓜',
'可可味,香料味',
'这是一款典雅、丰富并具有深度的咖啡,其精致的酸度与微妙的可可粉质感以及柔和的香料风味完美地平衡在了一起。'
,'拉丁美洲','水洗法','可可味,香料味',
'中等','中等','可可,苹果,焦糖,果仁','首选咖啡',399,'images/p5.jpg','images/lp5.jpg'
);
INSERT INTO product VALUES(NULL,'早餐综合',
'明亮,香气扑鼻',
'这款醇度清淡的综合咖啡活泼而清爽,唤醒你的味蕾,带给你明快的第一印象,让你焕然一新,开始新的一天。'
,'拉丁美洲','水洗法','明亮,香气扑鼻',
'较高','清淡','果仁,苹果,蓝莓,柠檬','首选咖啡,危地马拉安提瓜咖啡',399,'images/p1.jpg','images/lp1.jpg'
);
INSERT INTO product VALUES(NULL,'埃塞俄比亚',
'柑橘,可可味',
'这款醇度清淡的综合咖啡活泼而清爽,唤醒你的味蕾,带给你明快的第一印象,让你焕然一新,开始新的一天。'
,'拉丁美洲','水洗法','明亮,香气扑鼻',
'较高','清淡','果仁,苹果,蓝莓,柠檬','首选咖啡,危地马拉安提瓜咖啡',399,'images/p4.jpg','images/lp4.jpg'
);
INSERT INTO product VALUES(NULL,'意式烘焙',
'烘烤甜味,淡淡的烟熏味',
'这是一款醇度浓郁的多区域综合咖啡,经过比浓缩烘焙咖啡更深度的烘焙,它浓烈而香甜,并带有淡淡的烟熏风味。'
,'多区域','水洗法','烘烤甜味,淡淡的烟熏味',
'较低','中等','巧克力,焦糖,香料','浓缩烘焙咖啡,佛罗娜咖啡®',399,'images/p7.jpg','images/lp7.jpg'
);
INSERT INTO product VALUES(NULL,'浓缩烘焙',
'焦糖味,烘焙味',
'这款综合咖啡是我们所有浓缩咖啡饮料的核心,其特点是浓郁的香味以及柔和的酸度,且与浓厚的焦糖香甜味平衡搭配。'
,'多区域','水洗法','焦糖味,烘焙味',
'较低','厚重','焦糖,香料,巧克力,果仁','佛罗娜咖啡®,危地马拉安提瓜咖啡',399,'images/p3.jpg','images/lp3.jpg'
);
INSERT INTO product VALUES(NULL,'佛罗娜®咖啡',
'烘烤甜味',
'这是一款来自拉丁美洲咖啡和亚洲/太平洋地区咖啡的综合咖啡,醇度厚重,并带有意式烘焙咖啡的香甜味。'
,'多区域','水洗法,半水洗法','烘烤甜味',
'中等','厚重','牛奶和黑巧克力、焦糖','浓缩烘焙咖啡',399,'images/p12.jpg','images/lp12.jpg'
);
INSERT INTO product VALUES(NULL,'低因祥龙综合',
'泥土芳香,草药味,香料味',
'具有浓郁的草药味、香料味和泥土芳香;这款浓郁而平和的亚洲/太平洋地区综合咖啡展现出厚重的醇度以及令人惊奇的酸度之间的良好平衡。'
,'亚洲/太平洋','水洗法,半水洗法','泥土芳香,草药味,香料味',
'较低','厚重','肉桂,燕麦片,枫糖,黄油面包','苏门答腊咖啡',399,'images/p9.jpg','images/lp9.jpg'
);
INSERT INTO product VALUES(NULL,'苏门答腊',
'草药味,泥土芳香',
'带有强烈的泥土芳香,风味异常集中;醇度厚重而浓郁,苏门答腊咖啡是我们非常畅销的其中一款单品咖啡。'
,'亚洲/太平洋','半水洗法','草药味,泥土芳香',
'较低','厚重','肉桂,燕麦片,枫糖,黄油,太妃糖','低因祥龙综合咖啡®',399,'images/p11.jpg','images/lp11.jpg'
); |
CREATE TABLE "departments" (
"dept_no" VARCHAR(4) NOT NULL,
"dept_name" VARCHAR(50) NOT NULL,
CONSTRAINT "pk_departments" PRIMARY KEY (
"dept_no"
)
);
-- Testing departments
SELECT *
FROM departments
CREATE TABLE "dept_emp" (
"emp_no" INTEGER NOT NULL,
"dept_no" VARCHAR(4) NOT NULL,
"from_date" VARCHAR(10) NOT NULL,
"to_date" VARCHAR(10) NOT NULL
);
--Testing dept_emp
SELECT *
FROM dept_emp
CREATE TABLE "dept_manager" (
"dept_no" VARCHAR(4) NOT NULL,
"emp_no" INTEGER NOT NULL,
"from_date" VARCHAR(10) NOT NULL,
"to_date" VARCHAR(10) NOT NULL
);
--Testing dept_manager
SELECT *
FROM dept_manager
CREATE TABLE "employees" (
"emp_no" INTEGER NOT NULL,
"birth_date" VARCHAR(10) NOT NULL,
"first_name" VARCHAR NOT NULL,
"last_name" VARCHAR NOT NULL,
"gender" VARCHAR NOT NULL,
"hire_date" VARCHAR(10) NOT NULL,
CONSTRAINT "pk_employees" PRIMARY KEY (
"emp_no"
)
);
--Testing employees
SELECT *
FROM employees
CREATE TABLE "salaries" (
"emp_no" INTEGER NOT NULL,
"salary" INTEGER NOT NULL,
"from_date" VARCHAR(10) NOT NULL,
"to_date" VARCHAR(10) NOT NULL
);
--Testing salaries
SELECT *
FROM salaries
CREATE TABLE "titles" (
"emp_no" INTEGER NOT NULL,
"title" VARCHAR(50) NOT NULL,
"from_date" VARCHAR(10) NOT NULL,
"to_date" VARCHAR(10) NOT NULL
);
--Testing titles
SELECT *
FROM titles
--Creating alter tables
ALTER TABLE "dept_emp" ADD CONSTRAINT "fk_dept_emp_emp_no" FOREIGN KEY("emp_no")
REFERENCES "employees" ("emp_no");
ALTER TABLE "dept_emp" ADD CONSTRAINT "fk_dept_emp_dept_no" FOREIGN KEY("dept_no")
REFERENCES "departments" ("dept_no");
ALTER TABLE "dept_manager" ADD CONSTRAINT "fk_dept_manager_emp_no" FOREIGN KEY("emp_no")
REFERENCES "employees" ("emp_no");
ALTER TABLE "salaries" ADD CONSTRAINT "fk_salaries_emp_no" FOREIGN KEY("emp_no")
REFERENCES "employees" ("emp_no");
ALTER TABLE "titles" ADD CONSTRAINT "fk_titles_emp_no" FOREIGN KEY("emp_no")
REFERENCES "employees" ("emp_no");
--Answering questions
--1. List the following details of each employee:
--employee number, last name, first name, gender, and salary.
SELECT e.emp_no,e.last_name, e.first_name, e.gender,s.salary
FROM employees e
JOIN salaries s
ON (e.emp_no = s.emp_no);
--2. List employees who were hired in 1986.
SELECT *
FROM employees
WHERE hire_date LIKE '1986%';
--3. List the manager of each department with the following information:
--department number, department name, the manager's employee number, last name,
--first name, and start and end employment dates.
SELECT m.dept_no, d.dept_name,m.emp_no, e.last_name, e.first_name, m.from_date, m.to_date
FROM dept_manager m
JOIN departments d
ON (m.dept_no = d.dept_no)
JOIN employees e
ON (m.emp_no = e.emp_no);
--4. List the department of each employee with the following information:
--employee number, last name, first name, and department name.
SELECT e.emp_no, e.last_name, e.first_name, d.dept_name
FROM employees e
JOIN dept_emp m
ON (e.emp_no = m.emp_no)
JOIN departments d
ON (m.dept_no = d.dept_no);
--5. List all employees whose first name is "Hercules" and last names begin with "B."
SELECT *
FROM employees
WHERE first_name = 'Hercules'
AND last_name LIKE 'B%';
--6. List all employees in the Sales department, including their employee number,
--last name, first name, and department name.
SELECT e.emp_no, e.last_name, e.first_name, d.dept_name
FROM employees e
JOIN dept_emp m
ON (e.emp_no = m.emp_no)
JOIN departments d
ON (m.dept_no = d.dept_no)
WHERE d.dept_name ='Sales';
--7. List all employees in the Sales and Development departments,
--including their employee number, last name, first name, and department name.
SELECT e.emp_no, e.last_name, e.first_name, d.dept_name
FROM employees e
JOIN dept_emp m
ON (e.emp_no = m.emp_no)
JOIN departments d
ON (m.dept_no = d.dept_no)
WHERE d.dept_name ='Sales'
OR d.dept_name ='Development';
--8. In descending order, list the frequency count of employee last names,
--i.e., how many employees share each last name.
SELECT e.last_name,
COUNT (e.last_name)
FROM employees e
GROUP BY e.last_name
ORDER BY count DESC;
|
"isbn13", "author", "title", "publisher", "pubdate", "price", "binding", "alt", "author_intro", "summary"
CREATE DATABASE dushu DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
create table dushu.book_information(
id int primary key auto_increment,
isbn13 varchar(20) comment 'ISBN号',
author varchar(60) comment '作者',
translator varchar(20) comment '翻译者',
title varchar(100) comment '书籍名称',
publisher varchar(60) comment '出版社',
pubdate varchar(30) comment '出版时间',
price varchar(30) comment '书本定价',
binding varchar(30) comment '装订类别',
alt varchar(100) comment '豆瓣地址',
author_intro text comment '作者简介',
summary text comment '书籍简介',
add_time date comment '添加时间',
addr_id varchar(4) comment '书籍位置'
) character set = utf8;
create table dushu.rating(
id int primary key auto_increment,
isbn13 varchar(20) comment 'ISBN号',
max varchar(10) comment '最高分',
numRaters varchar(10) comment '评价者数量',
average varchar(10) comment '平均分',
min varchar(10)
) character set = utf8;
create table dushu.images(
id int primary key auto_increment,
isbn13 varchar(20) comment 'ISBN号',
small varchar(100) comment '小图片',
large varchar(100) comment '大图片',
medium varchar(100) comment '中图片'
) character set = utf8;
create table dushu.tags(
id int primary key auto_increment,
isbn13 varchar(20) comment 'ISBN号',
count varchar(10) comment '参与人数',
name varchar(20) comment '标签名称',
title varchar(20) comment '标签title'
) character set = utf8;
create table dushu.address(
id int primary key auto_increment,
address varchar(200) comment '书籍地址'
) character set = utf8; |
-- триггер для проверки возраста пользователя перед обновлением
CREATE TRIGGER check_user_age_before_update BEFORE INSERT ON worker
FOR EACH ROW
begin
IF NEW.birthday >= CURRENT_DATE() THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Update Canceled. Birthday must be in the past!';
END IF;
END;
-- Проверка
-- не подходящая дата
INSERT INTO `worker`
VALUES
('17','Гривень','Олеся','Олесевич','f','2022-03-16','griv.d.d@mail.ru','9035111127');
-- триггер для проверки наличия только одного генерального директора перед обновлением
CREATE TRIGGER In_The_End_There_Can_Be_Only_One -- (с)Highlander
BEFORE INSERT
ON profiles FOR EACH ROW
begin
IF NEW.position ='Генеральный директор' THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'There can be only one CEO!';
END IF;
END;
-- Проверка
-- не подходящая должность
INSERT INTO `worker`
VALUES
('17','Гривень','Олеся','Олесевич','f','1988-03-16','griv.d.d@mail.ru','9035111127');
INSERT INTO `profiles`
VALUES
('17','15','16','3',NULL,'4',NULL,'Генеральный директор','2012-12-10 09:28:07','Организация производства','planning','30',NOW());
|
-- CreateTable
CREATE TABLE `post` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`title` VARCHAR(191) NOT NULL,
`post` VARCHAR(500) NOT NULL,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updated_at` DATETIME(3) NOT NULL,
`user_id` INTEGER NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- AddForeignKey
ALTER TABLE `post` ADD FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
/**
*
* @author Alexey
* @name SumOfSums
* @manual
*/
Select t1.lc_id, sum(t.calc) AS sal_calc, sum(t.benefit) AS sal_benefit, sum(t.recalc) AS sal_recalc
, sum(t.full_calc) AS sal_full_calc
From per_sums t
Inner Join lc_flat_services t1 on t1.lc_flat_services_id = t.flat_service_id and :accountid = t1.account_id
Inner Join Calc_object q on q.lc_id = t1.lc_id
Where :dateid = t.date_id
Group by t1.lc_id |
update books
set instock = false
where id=$1; |
-- Create public schema
CREATE SCHEMA IF NOT EXISTS public;
-- Set public as current search path
SET search_path TO public; -- Create tables
-- First create the guild table
CREATE TABLE IF NOT EXISTS "Guilds" (
"id" SERIAL PRIMARY KEY NOT NULL,
"guildID" VARCHAR(19) UNIQUE NOT NULL,
"createRoleIDs" VARCHAR(19)[] DEFAULT ARRAY[]::TEXT[] NOT NULL,
"defaultCardChannelID" VARCHAR(19) UNIQUE NOT NULL
);
-- Create the reminders table if not available
CREATE TABLE IF NOT EXISTS "Reminders" (
"id" SERIAL PRIMARY KEY NOT NULL,
"createdAt" TIMESTAMP NOT NULL DEFAULT now(),
"channelID" VARCHAR(19) NOT NULL,
"content" TEXT NOT NULL,
"guildID" VARCHAR(19) NOT NULL,
"reminderID" VARCHAR(19) NOT NULL,
"interval" INTEGER NOT NULL DEFAULT 0,
"timestamp" TIMESTAMP NOT NULL DEFAULT now(),
"userID" VARCHAR(19) NOT NULL,
"embedEnabled" BOOLEAN NOT NULL DEFAULT true
);
-- Create the events table if not available
CREATE TABLE IF NOT EXISTS "Events" (
"id" SERIAL PRIMARY KEY NOT NULL,
"activity" TEXT NOT NULL,
"cardChannelID" VARCHAR(19),
"cardMessageID" VARCHAR(19),
"allowedRoleIDs" VARCHAR(19)[] DEFAULT ARRAY[]::TEXT[] NOT NULL,
"alertRoleIDs" VARCHAR(19)[] DEFAULT ARRAY[]::TEXT[] NOT NULL,
"attendeeIDs" VARCHAR(19)[] DEFAULT ARRAY[]::TEXT[] NOT NULL,
"authorID" VARCHAR(19),
"backgroundURL" TEXT,
"createdAt" TIMESTAMP NOT NULL DEFAULT now(),
"denialIDs" VARCHAR(19)[] DEFAULT ARRAY[]::TEXT[] NOT NULL,
"description" TEXT NOT NULL,
"dmReminders" BOOLEAN NOT NULL DEFAULT false,
"duration" INTEGER NOT NULL DEFAULT 0,
"endTimestamp" TIMESTAMP NOT NULL DEFAULT now(),
"executedReminders" INTEGER[] DEFAULT ARRAY[]::INTEGER[] NOT NULL,
"eventID" INTEGER UNIQUE NOT NULL DEFAULT 0,
"frequency" INTEGER NOT NULL DEFAULT 0,
"game" TEXT NOT NULL,
"guildID" VARCHAR(19),
"hasStarted" BOOLEAN NOT NULL DEFAULT false,
"isRecurring" BOOLEAN NOT NULL DEFAULT false,
"maxAttendees" INTEGER NOT NULL DEFAULT 5,
"maybeIDs" VARCHAR(19)[] DEFAULT ARRAY[]::TEXT[] NOT NULL,
"minutesFromNow" INTEGER NOT NULL DEFAULT 0,
"platform" TEXT NOT NULL,
"reminders" INTEGER[] DEFAULT ARRAY[]::INTEGER[] NOT NULL,
"removeRecurringAttendees" BOOLEAN NOT NULL DEFAULT false,
"startTimestamp" TIMESTAMP NOT NULL DEFAULT now(),
"template" TEXT,
"title" TEXT NOT NULL,
"waitingListIDs" VARCHAR(19)[] DEFAULT ARRAY[]::TEXT[] NOT NULL
);
|
/* LAHMAN BASEBALL ANALYSIS */
--Q1 --
-- What range of years for baseball games played does the provided database cover?
select min(yearid), max(yearid)
from appearances;
--Q2 --
--Find the name and height of the shortest player in the database.
--How many games did he play in? What is the name of the team for which he played?
SELECT DISTINCT ppl.namefirst, ppl.namelast, app.g_all AS games, t.name AS team
FROM people AS ppl
LEFT JOIN appearances AS app
ON ppl.playerid = app.playerid
RIGHT JOIN teams AS t
ON app.teamid = t.teamid
WHERE ppl.height IN (SELECT MIN(height) FROM people);
/* 3. Find all players in the database who played at Vanderbilt University.
Create a list showing each player’s first and last names as well as the total salary
they earned in the major leagues. Sort this list in descending order by the total
salary earned. Which Vanderbilt player earned the most money in the majors? */
--Q3--Option1
WITH vandy_players AS (
SELECT DISTINCT playerid
FROM collegeplaying
WHERE schoolid = (SELECT schoolid
FROM schools
WHERE schoolname iLIKE '%vand%'))
SELECT
namefirst AS first_name,
namelast AS last_name,
SUM(salary::decimal::money) AS total_major_league_salary
FROM vandy_players
LEFT JOIN people
USING (playerid)
LEFT JOIN salaries
USING (playerid)
GROUP BY namefirst,namelast
HAVING SUM(salary) >0
ORDER BY SUM(salary) DESC;
--Q3-- Option2
WITH vandy_salaries as (SELECT DISTINCT namefirst AS namefirst, namelast, schoolid, salaries.yearid AS yearid, salary
FROM people INNER JOIN collegeplaying USING(playerid)
INNER JOIN salaries USING(playerid)
WHERE schoolid = 'vandy'
ORDER BY namefirst, namelast, yearid)
SELECT namefirst, namelast, schoolid, SUM(salary)::text::money AS total_salary
FROM vandy_salaries
GROUP BY namefirst, namelast, schoolid
ORDER BY total_salary DESC;
-- Q3 MISC - To confirm David Price's lifetime salary 81,851,296
SELECT SUM(salary) FROM SALARIES where playerid = 'priceda01' GROUP BY playerid;
SELECT * FROM people WHERE namefirst='David' AND namelast='Price'
SELECT * FROM collegeplaying LIMIT 10;
/*Q4
Using the fielding table, group players into three groups based on their position:
label players with position OF as "Outfield", those with position "SS", "1B", "2B",
and "3B" as "Infield", and those with position "P" or "C" as "Battery".
Determine the number of putouts made by each of these three groups in 2016. */
WITH calculation AS (
SELECT playerid, pos,
CASE WHEN pos = 'OF' THEN 'Outfield'
WHEN pos = 'SS' OR pos ='1B' OR pos = '2B' OR pos = '3B' THEN 'Infield'
ELSE 'Battery' END AS position,
po AS PutOut,
yearid
FROM fielding
WHERE yearid = '2016')
SELECT position, SUM(putout) AS number_putouts
FROM calculation
GROUP BY position;
/* Q5
Find the average number of strikeouts per game by decade since 1920.
Round the numbers you report to 2 decimal places.
Do the same for home runs per game. Do you see any trends? */
SELECT teams.yearid /10*10 as decade, sum(so) AS total_strike_out,
Sum(g) as total_games,
round(sum(so)::decimal / sum(g),2)::decimal as average_strike_out
FROM teams
WHERE yearid >= '1920'
GROUP BY yearid/10*10
ORDER BY decade DESC
-- Home Runs
SELECT teams.yearid /10*10 as decade, sum(hr) AS homerun,
Sum(g) as total_games,
round(sum(hr)::decimal / sum(g),2)::decimal as average_homerun
FROM teams
WHERE yearid >= '1920'
GROUP BY yearid/10*10
ORDER BY decade DESC
/* Q6
Find the player who had the most success stealing bases in 2016, where success is measured
as the percentage of stolen base attempts which are successful.
(A stolen base attempt results either in a stolen base or being caught stealing.)
Consider only players who attempted at least 20 stolen bases */
--Q6--Option1
SELECT DISTINCT b.playerid,
CONCAT(p.namefirst,' ',p.namelast) AS player_name,
(b.sb) AS stolen_bases,
(b.cs) AS caught_stealing,
b.sb+b.cs AS sb_cs,
ROUND(CAST(float8 (b.sb/(b.sb+b.cs)::float*100) AS NUMERIC),2) AS successful_stolen_bases_percent
FROM batting AS b
LEFT JOIN people AS p
ON b.playerid = p.playerid
WHERE b.yearid = '2016'
GROUP BY b.playerid, p.namefirst, p.namelast, b.sb, b.cs
HAVING SUM(b.sb+b.cs) >= 20
ORDER BY successful_stolen_bases_percent DESC
--Q6--Option2
select distinct(p.playerid),
p.namefirst, p.namelast,
a.yearid, b.sb,
cast(b.sb as numeric) + cast(b.cs as numeric) as total_attempts,
round(cast(b.sb as numeric) /(cast(b.sb as numeric) + cast(b.cs as numeric)),2) as percentage_stole
from people as p left join appearances as a
on p.playerid = a.playerid
left join batting as b
on p.playerid = b.playerid
where a.yearid = 2016
and b.yearid =2016
and cast(b.sb as numeric) + cast(b.cs as numeric) >= 20
order by percentage_stole desc;
/* Q7 */
/* Q7, part 1
From 1970 – 2016, what is the largest number of wins for a team
that did not win the world series during that time frame? */
SELECT yearid, teamid, MAX(w) as max_wins
FROM teams
WHERE
yearid BETWEEN 1970 AND 2016
AND teamid NOT IN (
SELECT teamid
FROM teams
WHERE wswin = 'Y'
AND yearid >= 1970 AND yearid <=2016)
GROUP BY yearid, teamid
ORDER BY MAX(w)DESC
LIMIT 1;
/* Q7 - part2
What is the smallest number of wins for a team that did win the world series?
Doing this will probably result in an unusually small number of wins for a world series champion –
determine why this is the case. Then redo your query, excluding the problem year.
The smallest number of wins was in 1981 with the Toronto Blue Jays with 37 wins.
1981 was the year of the player's strike and the season was cut short. */
SELECT yearid, teamid, MIN(w) as min_wins
FROM teams
WHERE
yearid BETWEEN 1970 AND 2016
AND teamid IN (
SELECT teamid
FROM teams
WHERE wswin = 'Y'
AND yearid BETWEEN 1970 AND 2016)
GROUP BY yearid, teamid
ORDER BY MIN(w)
LIMIT 1;
/* Q7 - part 3 when you remove 1981 from the query, the lowest number of
wins is from Detroit Tigers in 2003 with 43 wins*/
SELECT yearid, teamid, MIN(w) as min_wins
FROM teams
WHERE (yearid BETWEEN 1970 AND 1980 OR yearid BETWEEN 1982 AND 2016)
AND teamid IN (
SELECT teamid
FROM teams
WHERE wswin = 'Y'
AND yearid BETWEEN 1970 AND 2016)
GROUP BY yearid, teamid
ORDER BY MIN(w)
LIMIT 1;
/* Q7 - part 4 How often from 1970 – 2016 was it the case that a team with the most wins also won the world series?
What percentage of the time? */
WITH most_wins AS (
SELECT
yearid,
MAX(w) AS max_w
FROM teams
WHERE yearid BETWEEN 1970 AND 2016
GROUP BY yearid
ORDER BY yearid),
teams_most_wins AS (
SELECT t.yearid,
t.teamid
FROM teams AS t
INNER JOIN most_wins
ON t.yearid = most_wins.yearid AND t.w = most_wins.max_w),
ws_wins AS (
SELECT
yearid,
teamid
FROM teams
WHERE wswin = 'Y'
AND yearid BETWEEN 1970 AND 2016),
combined_stats AS (
SELECT
teams_most_wins.yearid,
teams_most_wins.teamid AS most_wins_team,
ws_wins.teamid AS ws_wins_team
FROM teams_most_wins
LEFT JOIN ws_wins
USING(yearid)
ORDER BY yearid)
SELECT
COUNT(CASE WHEN cs.most_wins_team = cs.ws_wins_team THEN 1 END) AS count_most_wins_also_ws_winner,
CONCAT(ROUND(100*(COUNT(CASE WHEN cs.most_wins_team = cs.ws_wins_team THEN 1 END)::decimal) / (COUNT(Distinct yearid)::decimal),2),'%') AS percentage_most_wins_also_ws_winner
FROM combined_stats AS cs;
/* Q8 - Using the attendance figures from the homegames table,
find the teams and parks which had the top 5 average attendance per game in 2016
where average attendance is defined as total attendance divided by number of games).
Only consider parks where there were at least 10 games played. Report the park name,
team name, and average attendance. Repeat for the lowest 5 average attendance. */
WITH avg_attend AS (SELECT park, team, attendance/games AS avg_attendance
FROM homegames
WHERE year = 2016
AND games >= 10),
avg_attend_full AS (SELECT park_name, name as team_name, avg_attendance
FROM avg_attend INNER JOIN teams ON avg_attend.team = teams.teamid
INNER JOIN parks ON avg_attend.park = parks.park
WHERE teams.yearid = 2016
GROUP BY park_name, avg_attendance, name),
top_5 AS (SELECT *, 'top_5' AS category
FROM avg_attend_full
ORDER BY avg_attendance DESC
LIMIT 5),
bottom_5 AS (SELECT *, 'bottom_5' AS category
FROM avg_attend_full
ORDER BY avg_attendance
LIMIT 5)
SELECT *
FROM top_5
UNION ALL
SELECT *
FROM bottom_5;
/* Q9 - Which managers have won the TSN Manager of the Year award in both the
National League (NL) and the American League (AL)? Give their full name and the teams
that they were managing when they won the award. */
WITH mngr_list AS (SELECT playerid, awardid, COUNT(DISTINCT lgid) AS lg_count
FROM awardsmanagers
WHERE awardid = 'TSN Manager of the Year'
AND lgid IN ('NL', 'AL')
GROUP BY playerid, awardid
HAVING COUNT(DISTINCT lgid) = 2),
mngr_full AS (SELECT playerid, awardid, lg_count, yearid, lgid
FROM mngr_list INNER JOIN awardsmanagers USING(playerid, awardid))
SELECT DISTINCT namegiven, namelast, name AS team_name, mngr_full.lgid, mngr_full.yearid
FROM mngr_full INNER JOIN people USING(playerid)
INNER JOIN managers USING(playerid, yearid, lgid)
INNER JOIN teams ON mngr_full.yearid = teams.yearid AND mngr_full.lgid = teams.lgid AND managers.teamid = teams.teamid;
/* Q10 - Analyze all the colleges in the state of Tennessee. Which college has had the most
success in the major leagues. Use whatever metric for success you like - number of players,
number of games, salaries, world series wins, etc. */
WITH tn_schools AS (SELECT schoolname, schoolid
FROM schools
WHERE schoolstate = 'TN'
GROUP BY schoolname, schoolid)
SELECT schoolname, COUNT(DISTINCT playerid) AS player_count, SUM(salary)::text::money AS total_salary, (SUM(salary)/COUNT(DISTINCT playerid))::text::money AS money_per_player
FROM tn_schools INNER JOIN collegeplaying USING(schoolid)
INNER JOIN people USING(playerid)
INNER JOIN salaries USING(playerid)
GROUP BY schoolname
ORDER BY money_per_player DESC;
/* Q11 - Is there any correlation between number of wins and team salary? Use data from 2000
and later to answer this question. As you do this analysis, keep in mind that salaries across
the whole league tend to increase together, so you may want to look on a year-by-year basis. */
WITH team_year_sal_w AS (SELECT teamid, yearid, SUM(salary) AS total_team_sal, AVG(w)::integer AS w
FROM salaries INNER JOIN teams USING(yearid, teamid)
WHERE yearid >= 2000
GROUP BY yearid, teamid)
SELECT yearid, CORR(total_team_sal, w) AS sal_win_corr
--correlation results intrepretation: 0 means no correlation, 1 means exact correlation where you can make perfect predictions
FROM team_year_sal_w
GROUP BY yearid
ORDER BY yearid;
/* Q12 In this question, you will explore the connection between number of wins and attendance.
Does there appear to be any correlation between attendance at home games and number of wins?
As you scroll through the results and see the average attendance numbers decrease
you would expect to see percent_wins also decrease if they were correlated, but that is
not the case so there doesn't appear to be a correlation between home game attendance
and number of wins */
SELECT CORR(homegames.attendance, w) AS corr_attend_w
FROM teams INNER JOIN homegames ON teamid = team AND yearid = year
WHERE homegames.attendance IS NOT NULL
/* Q12 - part 2 - Do teams that win the world series see a boost in attendance the following year? */
--Q12--part2--Option1
SELECT
t.yearid,
t.teamid,
SUM(h.attendance) AS attendance_wswin_yr,
SUM(h2.attendance) AS yr_after_attendance,
SUM(h2.attendance) - SUM(h.attendance) AS attendance_diff
FROM teams AS t
JOIN homegames AS h
ON t.teamid=h.team AND t.yearid=h.year
JOIN homegames AS h2
ON t.teamid=h2.team and (t.yearid+1)=h2.year
WHERE wswin = 'Y'
GROUP BY t.yearid, t.teamid
ORDER BY yearid
--Q12--part2--Option2 with a summary approach
SELECT AVG(hg_2.attendance - hg_1.attendance) AS avg_attend_increase,
stddev_pop(hg_2.attendance - hg_1.attendance) AS stdev_attend_increase,
MAX(hg_2.attendance - hg_1.attendance) AS max_attend_increase,
MIN(hg_2.attendance - hg_1.attendance) AS min_attend_increase
FROM teams INNER JOIN homegames AS hg_1 ON teams.yearid = hg_1.year AND teams.teamid = hg_1.team
INNER JOIN homegames AS hg_2 ON teams.yearid + 1 = hg_2.year AND teams.teamid = hg_2.team
WHERE wswin = 'Y'
AND hg_1.attendance > 0
AND hg_2.attendance > 0;
/* Q12 - Part3 - What about teams that made the playoffs?
Making the playoffs means either being a division winner or a wild card winner. */
--Q12--Part3--Option1
SELECT
t.yearid,
t.teamid,
SUM(h.attendance) AS attendance_divwin_yr,
SUM(h2.attendance) AS yr_after_attendance,
SUM(h2.attendance) - SUM(h.attendance) AS attendance_diff
FROM teams AS t
JOIN homegames AS h
ON t.teamid=h.team AND t.yearid=h.year
JOIN homegames AS h2
ON t.teamid=h2.team and (t.yearid+1)=h2.year
WHERE DivWin = 'Y' OR WcWin = 'Y'
GROUP BY t.yearid, t.teamid
ORDER BY yearid
--Q12--part 3--Option2 with a summary approach
SELECT AVG(hg_2.attendance - hg_1.attendance) AS avg_attend_increase,
stddev_pop(hg_2.attendance - hg_1.attendance) AS stdev_attend_increase,
MAX(hg_2.attendance - hg_1.attendance) AS max_attend_increase,
MIN(hg_2.attendance - hg_1.attendance) AS min_attend_increase
FROM teams INNER JOIN homegames AS hg_1 ON teams.yearid = hg_1.year AND teams.teamid = hg_1.team
INNER JOIN homegames AS hg_2 ON teams.yearid + 1 = hg_2.year AND teams.teamid = hg_2.team
WHERE (divwin = 'Y' OR wcwin = 'Y')
AND hg_1.attendance > 0
AND hg_2.attendance > 0;
/* Q13 - It is thought that since left-handed pitchers are more rare, causing batters to face them
less often, that they are more effective. Investigate this claim and present evidence to either
support or dispute this claim. First, determine just how rare left-handed pitchers are compared
with right-handed pitchers. Are left-handed pitchers more likely to win the Cy Young Award?
Are they more likely to make it into the hall of fame? */
WITH pitchers AS (SELECT *
FROM people INNER JOIN pitching USING(playerid)
INNER JOIN awardsplayers USING(playerid)
INNER JOIN halloffame USING(playerid))
SELECT (SELECT COUNT(DISTINCT playerid)::float
FROM pitchers WHERE throws = 'L')/COUNT(DISTINCT playerid)::float AS pct_left_pitch,
(SELECT COUNT(DISTINCT playerid)::float
FROM pitchers WHERE awardid = 'Cy Young Award')/COUNT(DISTINCT playerid)::float AS pct_pitch_cy_young,
((SELECT COUNT(DISTINCT playerid)::float
FROM pitchers WHERE awardid = 'Cy Young Award')/COUNT(DISTINCT playerid)::float) * ((SELECT COUNT(DISTINCT playerid)::float
FROM pitchers WHERE throws = 'L')/COUNT(DISTINCT playerid)::float) AS calc_pct_left_cy_young,
(SELECT COUNT(DISTINCT playerid)::float
FROM pitchers WHERE awardid = 'Cy Young Award' AND throws = 'L')/COUNT(DISTINCT playerid)::float AS actual_pct_left_cy_young,
(SELECT COUNT(DISTINCT playerid)::float
FROM pitchers WHERE inducted = 'Y')/COUNT(DISTINCT playerid)::float AS pct_hof,
((SELECT COUNT(DISTINCT playerid)::float
FROM pitchers WHERE inducted = 'Y')/COUNT(DISTINCT playerid)::float) * ((SELECT COUNT(DISTINCT playerid)::float
FROM pitchers WHERE throws = 'L')/COUNT(DISTINCT playerid)::float) AS calc_pct_left_hof,
(SELECT COUNT(DISTINCT playerid)::float
FROM pitchers WHERE inducted = 'Y' AND throws = 'L')/COUNT(DISTINCT playerid)::float AS actual_pct_left_hof
FROM pitchers;
|
CREATE TABLE IF NOT EXISTS `roles` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL,
`description` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `roles` (`id`, `name`, `description`) VALUES(1, 'login', 'Login privileges, granted after account confirmation');
INSERT INTO `roles` (`id`, `name`, `description`) VALUES(2, 'admin', 'Administrative user, has access to everything.');
CREATE TABLE IF NOT EXISTS `roles_users` (
`user_id` int(10) UNSIGNED NOT NULL,
`role_id` int(10) UNSIGNED NOT NULL,
PRIMARY KEY (`user_id`,`role_id`),
KEY `fk_role_id` (`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`email` varchar(254) NOT NULL,
`username` varchar(32) NOT NULL DEFAULT '',
`password` varchar(64) NOT NULL,
`logins` int(10) UNSIGNED NOT NULL DEFAULT '0',
`last_login` int(10) UNSIGNED,
`date_registration` int(10) UNSIGNED NOT NULL,
`phone` varchar(100),
`verified` int(1) UNSIGNED NOT NULL DEFAULT '0',
`accept_terms` int(1) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_username` (`username`),
UNIQUE KEY `uniq_email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `user_tokens` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` int(11) UNSIGNED NOT NULL,
`user_agent` varchar(40) NOT NULL,
`token` varchar(40) NOT NULL,
`created` int(10) UNSIGNED NOT NULL,
`expires` int(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_token` (`token`),
KEY `fk_user_id` (`user_id`),
KEY `expires` (`expires`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `roles_users`
ADD CONSTRAINT `roles_users_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `roles_users_ibfk_2` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE;
ALTER TABLE `user_tokens`
ADD CONSTRAINT `user_tokens_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;
CREATE TABLE IF NOT EXISTS `requests` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` int(32) NOT NULL,
`want_sum` float(10) NOT NULL,
`want_currency` int(3) NOT NULL,
`sell_sum` float(10) NOT NULL,
`sell_currency` int(3) NOT NULL,
`comment` varchar(255) NULL,
`date_created` DATETIME NOT NULL,
`method_id` int(3) NULL,
`country_id` int(3) NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `categories_currency` (
`id` int(3) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- INSERT INTO categories_currency VALUES(1,'Banks');
INSERT INTO categories_currency VALUES(2,'Electronic carrency');
INSERT INTO categories_currency VALUES(3,'Cryptocurrency');
INSERT INTO categories_currency VALUES(4,'Cash');
CREATE TABLE IF NOT EXISTS `currencies` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`category_id` int(3) NOT NULL,
`name` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- INSERT INTO currencies VALUES(0,1,'[20] Mizrahi Tefahot Bank');
-- INSERT INTO currencies VALUES(0,1,'[34] Arab Israel Bank');
-- INSERT INTO currencies VALUES(0,1,'[12] Bank Hapoalim');
-- INSERT INTO currencies VALUES(0,1,'[10] Bank Leumi Le-Israel');
-- INSERT INTO currencies VALUES(0,1,'[46] Bank Massad');
-- INSERT INTO currencies VALUES(0,1,'[54] Bank of Jerusalem');
-- INSERT INTO currencies VALUES(0,1,'[14] Bank Otsar Ha-hayal');
-- INSERT INTO currencies VALUES(0,1,'[52] Bank Poalei Agudat Israel');
-- INSERT INTO currencies VALUES(0,1,'[4] Bank Yahav');
-- INSERT INTO currencies VALUES(0,1,'[68] Dexia Israel Bank');
-- INSERT INTO currencies VALUES(0,1,'[11] Israel Discount Bank');
-- INSERT INTO currencies VALUES(0,1,'[17] Mercantile Discount Bank');
-- INSERT INTO currencies VALUES(0,1,'[31] The First International Bank of Israel');
-- INSERT INTO currencies VALUES(0,1,'[26] Ubank');
-- INSERT INTO currencies VALUES(0,1,'[13] Union Bank (Igud)');
INSERT INTO currencies VALUES(0,2,'WebMoney');
INSERT INTO currencies VALUES(0,2,'Yandex.Money');
INSERT INTO currencies VALUES(0,2,'Skrill');
INSERT INTO currencies VALUES(0,2,'PayPal');
INSERT INTO currencies VALUES(0,2,'Ukash');
INSERT INTO currencies VALUES(0,2,'Paysavecard');
INSERT INTO currencies VALUES(0,2,'Easypay');
INSERT INTO currencies VALUES(0,2,'OKpay');
INSERT INTO currencies VALUES(0,2,'Netteler');
INSERT INTO currencies VALUES(0,2,'Cellarix');
INSERT INTO currencies VALUES(0,2,'Perfect Money');
INSERT INTO currencies VALUES(0,2,'Liqpay');
INSERT INTO currencies VALUES(0,2,'EgoPay');
INSERT INTO currencies VALUES(0,2,'Qiwi');
INSERT INTO currencies VALUES(0,3,'Bitcoin');
INSERT INTO currencies VALUES(0,3,'Litecoin');
INSERT INTO currencies VALUES(0,3,'PPCoin');
INSERT INTO currencies VALUES(0,3,'Namecoin');
INSERT INTO currencies VALUES(0,4,'ILS');
INSERT INTO currencies VALUES(0,4,'USD');
INSERT INTO currencies VALUES(0,4,'EUR');
INSERT INTO currencies VALUES(0,4,'Mezuman BeZman');
CREATE TABLE IF NOT EXISTS `methods` (
`id` int(3) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `methods_requests` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`request_id` int(10) NOT NULL,
`method_id` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO methods VALUES(0,'Cash');
INSERT INTO methods VALUES(0,'[20] Mizrahi Tefahot Bank');
INSERT INTO methods VALUES(0,'[34] Arab Israel Bank');
INSERT INTO methods VALUES(0,'[12] Bank Hapoalim');
INSERT INTO methods VALUES(0,'[10] Bank Leumi Le-Israel');
INSERT INTO methods VALUES(0,'[46] Bank Massad');
INSERT INTO methods VALUES(0,'[54] Bank of Jerusalem');
INSERT INTO methods VALUES(0,'[14] Bank Otsar Ha-hayal');
INSERT INTO methods VALUES(0,'[52] Bank Poalei Agudat Israel');
INSERT INTO methods VALUES(0,'[4] Bank Yahav');
INSERT INTO methods VALUES(0,'[68] Dexia Israel Bank');
INSERT INTO methods VALUES(0,'[11] Israel Discount Bank');
INSERT INTO methods VALUES(0,'[17] Mercantile Discount Bank');
INSERT INTO methods VALUES(0,'[31] The First International Bank of Israel');
INSERT INTO methods VALUES(0,'[26] Ubank');
INSERT INTO methods VALUES(0,'[13] Union Bank (Igud)');
CREATE TABLE IF NOT EXISTS `countries` (
`id` int(3) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO countries VALUES(0,'All world');
INSERT INTO countries VALUES(0,'Israel');
INSERT INTO countries VALUES(0,'USA');
CREATE TABLE IF NOT EXISTS `acceptors` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`request_id` int(11) NOT NULL,
`created_user_id` int(11) NOT NULL,
`accept_user_id` int(11) NOT NULL,
`date_created` DATETIME NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
ALTER TABLE `users` ADD COLUMN `phone` varchar(100) AFTER `username`;
ALTER TABLE `users` ADD COLUMN `date_registration` DATETIME AFTER `last_login`;
CREATE TABLE IF NOT EXISTS `ratings` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`accept_id` int(10) NOT NULL,
`from_user_id` int(10) NOT NULL,
`to_user_id` int(10) NOT NULL,
`rating` INT(1) NOT NULL,
`comment` varchar(254) NULL,
`date_created` DATETIME NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT INTO `ratings` VALUES(0,11,2,'First rating',NOW());
***
requests.user_id => requests.user_created_id
active or not in requests
VasyaVasya
BabraBabra
[11/12/13, 1:21:18 PM] Alen Kaminski: Bank Code Name
20 Mizrahi Tefahot Bank
34 Arab Israel Bank
12 Bank Hapoalim
10 Bank Leumi Le-Israel
46 Bank Massad
54 Bank of Jerusalem
14 Bank Otsar Ha-hayal
52 Bank Poalei Agudat Israel
4 Bank Yahav
68 Dexia Israel Bank
11 Israel Discount Bank
17 Mercantile Discount Bank
31 The First International Bank of Israel
26 Ubank
13 Union Bank (Igud)
[11/12/13, 1:21:26 PM] Alen Kaminski: lList of bank Israel |
CREATE PROCEDURE SSHARM17."AddHealthSupporterProc"(hs_ssn IN HEALTHSUPPORTER.SSN%TYPE,
hs_contactnumber IN HEALTHSUPPORTER.CONTACTNUMBER%TYPE
)
AS
BEGIN
INSERT INTO HEALTHSUPPORTER (SSN, CONTACTNUMBER) VALUES(hs_ssn, hs_contactnumber);
COMMIT;
END; |
CREATE DATABASE identity_registry CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE USER 'idreg'@'localhost' IDENTIFIED BY 'idreg';
GRANT ALL PRIVILEGES ON identity_registry.* TO 'idreg'@'localhost' WITH GRANT OPTION;
CREATE USER 'idreg'@'%' IDENTIFIED BY 'idreg';
GRANT ALL PRIVILEGES ON identity_registry.* TO 'idreg'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
|
DROP TABLE order_items;
DROP TABLE orders;
|
CREATE DATABASE `today` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
/*创建表user*/
CREATE TABLE `user` (
`user_id` int NOT NULL AUTO_INCREMENT comment '用户ID',
`user_name` varchar(20) NOT NULL COMMENT '用户名(昵称)',
`password` varchar(16) NOT NULL COMMENT '用户密码,存放MD5加密后的信息',
`user_avatar_url` varchar(40) NOT NULL COMMENT '用户头像的路径',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=91 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*创建待办信息表*/
CREATE TABLE `todo` (
`todo_id` int NOT NULL AUTO_INCREMENT,
`schedule_id` int DEFAULT NULL COMMENT '关联的日程ID',
`user_id` int NOT NULL COMMENT '关联用户ID',
`todo_progress_rate` tinyint DEFAULT '0' COMMENT '当前待办完成进度',
`repeat_type` tinyint DEFAULT '0' COMMENT '重复类型',
`todo_state` tinyint DEFAULT '0' COMMENT '待办状态',
`type` tinyint DEFAULT '0' COMMENT '待办类型',
`priority` tinyint DEFAULT '0' COMMENT '待办优先级',
`begin_time` datetime DEFAULT NULL COMMENT '开始时间',
`end_time` datetime DEFAULT NULL COMMENT '截至时间',
`content` varchar(60) DEFAULT NULL COMMENT '待办内容',
PRIMARY KEY (`todo_id`) COMMENT '主键',
KEY `user_id` (`user_id`),
CONSTRAINT `todo_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*创建父子待办信息表*/
CREATE TABLE `todorealationship` (
`child_todo_id` int NOT NULL COMMENT '子待办ID,不为空',
`parent_todo_id` int NOT NULL COMMENT '父待办,不为空',
PRIMARY KEY (`child_todo_id`,`parent_todo_id`),
KEY `parent_todo_id` (`parent_todo_id`),
CONSTRAINT `todorealationship_ibfk_1` FOREIGN KEY (`child_todo_id`) REFERENCES `todo` (`todo_id`),
CONSTRAINT `todorealationship_ibfk_2` FOREIGN KEY (`parent_todo_id`) REFERENCES `todo` (`todo_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*创建日程表*/
CREATE TABLE `schedule` (
`schedule_id` int NOT NULL COMMENT '日程ID',
`user_id` int NOT NULL COMMENT '关联用户ID',
`content` varchar(60) NOT NULL COMMENT '日程内容',
`begin_time` datetime DEFAULT NULL COMMENT '开始时间',
`end_time` datetime DEFAULT NULL COMMENT '截至时间',
`repeat_type` tinyint DEFAULT NULL COMMENT '重复类型',
`alarm_type` tinyint DEFAULT NULL COMMENT '提醒类型',
`schedule_type` tinyint DEFAULT NULL COMMENT '日程类型',
PRIMARY KEY (`schedule_id`,`user_id`),
KEY `user_id` (`user_id`),
CONSTRAINT `schedule_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*创建工作日志表*/
CREATE TABLE `worklog` (
`user_id` int NOT NULL COMMENT '父待办ID',
`date` date NOT NULL COMMENT '日期',
`tomato_clock_score` tinyint DEFAULT NULL COMMENT '当天番茄钟执行度',
`schedule_score` tinyint DEFAULT NULL COMMENT '当天日程时间块执行度',
`experience` varchar(100) DEFAULT NULL COMMENT '当天工作经验与日志',
PRIMARY KEY (`user_id`,`date`) COMMENT '用户ID+date作为主键',
CONSTRAINT `worklog_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*创建番茄钟信息表*/
CREATE TABLE `tomatoclock` (
`tomato_clock_id` int NOT NULL AUTO_INCREMENT COMMENT '自增的番茄钟ID',
`todo_id` int DEFAULT NULL COMMENT '关联待办ID',
`type` tinyint DEFAULT NULL COMMENT '番茄钟的类型',
`singel_duration` tinyint DEFAULT NULL COMMENT '单次时长',
`begin_time` datetime NOT NULL COMMENT '开始时间',
`user_id` int NOT NULL COMMENT '关联的用户ID',
`singel_rest_duration` tinyint DEFAULT NULL COMMENT '单词休息时长',
`repeat_times` tinyint DEFAULT NULL COMMENT '重复次数',
`summary` varchar(60) DEFAULT NULL COMMENT '总结',
`bgm_url` varchar(60) DEFAULT NULL COMMENT 'bgmURL',
PRIMARY KEY (`tomato_clock_id`,`user_id`),
KEY `user_id` (`user_id`),
CONSTRAINT `tomatoclock_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*创建番茄钟状态变化记录表*/
CREATE TABLE `tomatoclockstaterecord` (
`state_type` tinyint NOT NULL DEFAULT '0' COMMENT '状态类型',
`time` datetime NOT NULL COMMENT '状态变化时间',
`tomato_clock_id` int NOT NULL COMMENT '关联番茄钟ID',
PRIMARY KEY (`state_type`,`time`,`tomato_clock_id`),
KEY `tomato_clock_id` (`tomato_clock_id`),
CONSTRAINT `tomatoclockstaterecord_ibfk_1` FOREIGN KEY (`tomato_clock_id`) REFERENCES `tomatoclock` (`tomato_clock_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
CREATE TABLE [display].[chat_queue_entry_8rows]
(
[active_display_value] NVARCHAR(MAX) NULL,
[schedule_display_value] NVARCHAR(MAX) NULL,
[average_wait_time_display_value] NVARCHAR(MAX) NULL,
[escalate_to_display_value] NVARCHAR(MAX) NULL,
[not_available_display_value] NVARCHAR(MAX) NULL,
[sys_updated_by_display_value] NVARCHAR(MAX) NULL,
[sys_id_display_value"] NVARCHAR(MAX) NULL,
[confirm_problem_display_value] NVARCHAR(MAX) NULL,
[sys_mod_count_display_value] NVARCHAR(MAX) NULL,
[initial_agent_response_display_value] NVARCHAR(MAX) NULL,
[assignment_group_display_value] NVARCHAR(MAX) NULL,
[name_display_value] NVARCHAR(MAX) NULL,
[question_display_value] NVARCHAR(MAX) NULL,
[sys_updated_on_display_value] NVARCHAR(MAX) NULL,
[sys_tags_display_value] NVARCHAR(MAX) NULL,
[sys_created_on_display_value] NVARCHAR(MAX) NULL,
[sys_created_by_display_value] NVARCHAR(MAX) NULL
) |
/* to use, type 'source db/db.sql' in the sql cmd prmpt*/
/* db.sql -> schema.sql -> seeds.sql*/
DROP DATABASE IF EXISTS election;
CREATE DATABASE election;
USE election; |
--
-- file name: execution_engine_profiles.sql
-- Auther: Sharon Dashet (sharon.dashet@hp.com)
-- Date: 08/04/2014
--
select node_name, operator_name,min(start_date) as min_start_date, max(end_date) as max_end_date, datediff(second,min(start_date),max(end_date)) as operator_execution_time_sec, datediff(second,min(min(start_date)) over(),max(max(end_date)) over()) as total_execution_time_sec
from
(SELECT node_name, operator_id,operator_name,counter_name,counter_value
,case when counter_name = 'start time' then (internal_to_timestamptz(counter_value)) else null end as start_date
,case when counter_name = 'end time' then (internal_to_timestamptz(counter_value)) else null end as end_date
FROM v_monitor.execution_engine_profiles
--WHERE counter_name='execution time (us)'
where (transaction_id, statement_id) IN
(SELECT transaction_id, statement_id FROM query_requests
WHERE session_id= (SELECT session_id FROM v_monitor.current_session_p)
AND is_executing=false order BY end_timestamp DESC LIMIT 1)
order by operator_name, counter_name
) a
group by node_name, operator_name
order by max_end_date;
|
-- MySQL dump 10.13 Distrib 5.7.17, for Win64 (x86_64)
--
-- Host: localhost Database: sotietkiem
-- ------------------------------------------------------
-- Server version 5.7.21-log
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `group`
--
DROP TABLE IF EXISTS `group`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `group` (
`idGroup` int(2) NOT NULL,
`ten_group` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`idGroup`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `group`
--
LOCK TABLES `group` WRITE;
/*!40000 ALTER TABLE `group` DISABLE KEYS */;
/*!40000 ALTER TABLE `group` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `khachhang`
--
DROP TABLE IF EXISTS `khachhang`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `khachhang` (
`IDKhachHang` varchar(10) COLLATE ucs2_unicode_ci NOT NULL,
`TenKhachHang` varchar(50) CHARACTER SET utf8 NOT NULL,
`DiaChi` varchar(45) COLLATE ucs2_unicode_ci NOT NULL,
`CMND` varchar(10) COLLATE ucs2_unicode_ci NOT NULL,
`NgaySinh` date DEFAULT NULL,
`QuocTich` varchar(45) COLLATE ucs2_unicode_ci NOT NULL,
`QueQuan` varchar(15) CHARACTER SET utf8 DEFAULT NULL,
`NgheNghiep` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
`IsActive` bit(1) DEFAULT b'1',
PRIMARY KEY (`IDKhachHang`)
) ENGINE=InnoDB DEFAULT CHARSET=ucs2 COLLATE=ucs2_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `khachhang`
--
LOCK TABLES `khachhang` WRITE;
/*!40000 ALTER TABLE `khachhang` DISABLE KEYS */;
INSERT INTO `khachhang` VALUES ('1','1','112','1','2018-03-22','','','',''),('2','','2','','2018-03-15','2','','',''),('3','2','2','','2018-03-21','2','','',''),('4','','4','','2018-03-14','','','','');
/*!40000 ALTER TABLE `khachhang` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `loaitietkiem`
--
DROP TABLE IF EXISTS `loaitietkiem`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `loaitietkiem` (
`IDLoaiTietKiem` int(1) NOT NULL,
`TenLTK` varchar(45) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Tên loại tiết kiệm',
`SoNgayRut` int(3) NOT NULL COMMENT 'Số ngày được rút tiền',
`LaiSuat` float NOT NULL,
`LaiSuatTruocHan` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
`KyHan` varchar(45) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Đơn vị tháng',
`GuiThem` bit(1) DEFAULT NULL COMMENT 'Gửi thêm - chế độ không thời hạn',
`IsActive` bit(1) NOT NULL DEFAULT b'1',
`IDThamSo` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`IDLoaiTietKiem`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `loaitietkiem`
--
LOCK TABLES `loaitietkiem` WRITE;
/*!40000 ALTER TABLE `loaitietkiem` DISABLE KEYS */;
/*!40000 ALTER TABLE `loaitietkiem` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `login`
--
DROP TABLE IF EXISTS `login`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `login` (
`user` varchar(50) CHARACTER SET utf8 NOT NULL,
`pass` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
`idGroup` int(2) DEFAULT NULL COMMENT 'id nhóm quyền',
PRIMARY KEY (`user`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `login`
--
LOCK TABLES `login` WRITE;
/*!40000 ALTER TABLE `login` DISABLE KEYS */;
INSERT INTO `login` VALUES ('b','c',2),('c','c',1);
/*!40000 ALTER TABLE `login` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `phieugui`
--
DROP TABLE IF EXISTS `phieugui`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `phieugui` (
`IDPhieuGui` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`IDSoTK` varchar(10) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Mã sổ tiết kiệm',
`SoTienGui` float NOT NULL,
`NgayGui` date NOT NULL,
`NguoiGuiTien` varchar(50) CHARACTER SET utf8 NOT NULL COMMENT 'Người gửi thay',
PRIMARY KEY (`IDPhieuGui`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `phieugui`
--
LOCK TABLES `phieugui` WRITE;
/*!40000 ALTER TABLE `phieugui` DISABLE KEYS */;
/*!40000 ALTER TABLE `phieugui` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `phieurut`
--
DROP TABLE IF EXISTS `phieurut`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `phieurut` (
`IDPhieuRut` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`IDSoTK` varchar(10) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Mã sổ tk',
`SoTienRut` float NOT NULL,
`NgayRut` date NOT NULL,
`NguoiRut` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`IDPhieuRut`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `phieurut`
--
LOCK TABLES `phieurut` WRITE;
/*!40000 ALTER TABLE `phieurut` DISABLE KEYS */;
/*!40000 ALTER TABLE `phieurut` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `sotietkiem`
--
DROP TABLE IF EXISTS `sotietkiem`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sotietkiem` (
`IDSTK` varchar(10) COLLATE utf8_unicode_ci NOT NULL COMMENT '''Mã stk''',
`SoTienGuiTK` float NOT NULL COMMENT 'Số tiền gửi ban đầu',
`NgayMo` date NOT NULL COMMENT '''Ngày mở sổ''',
`DongSo` tinyint(1) NOT NULL DEFAULT '0' COMMENT '''Kiểm tra sổ đã đóng hay chưa''',
`IDKH` varchar(10) COLLATE utf8_unicode_ci NOT NULL COMMENT '''Mã khách hàng''',
`IDLoaiTien` varchar(5) COLLATE utf8_unicode_ci NOT NULL COMMENT '''Mã loại tiền''',
`IDLoaiTietKiem` int(1) NOT NULL COMMENT '''Mã loại tiết kiệm''',
`NgayTinhLai` date DEFAULT NULL COMMENT 'Ngày tính lãi suất',
`NgayDenHan` date DEFAULT NULL COMMENT 'Ngày đến hạn rút lãi',
`TongTien` float NOT NULL COMMENT 'Tổng lãi suất + gốc',
`IsActive` bit(1) NOT NULL DEFAULT b'1',
PRIMARY KEY (`IDSTK`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `sotietkiem`
--
LOCK TABLES `sotietkiem` WRITE;
/*!40000 ALTER TABLE `sotietkiem` DISABLE KEYS */;
/*!40000 ALTER TABLE `sotietkiem` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `thamso`
--
DROP TABLE IF EXISTS `thamso`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `thamso` (
`IDQuyDinhSoTien` int(11) NOT NULL,
`TenQuyDinh` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
`SoTienGuiToiThieu` float NOT NULL,
`SoTienGuiToiDa` float NOT NULL,
`SoTienGuiThemToiThieu` float NOT NULL,
PRIMARY KEY (`IDQuyDinhSoTien`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `thamso`
--
LOCK TABLES `thamso` WRITE;
/*!40000 ALTER TABLE `thamso` DISABLE KEYS */;
/*!40000 ALTER TABLE `thamso` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `tinhlai`
--
DROP TABLE IF EXISTS `tinhlai`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tinhlai` (
`idTinhlai` int(11) NOT NULL,
`IDSTK` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`SoTienGoc` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
`TongLaiSuat` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`idTinhlai`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `tinhlai`
--
LOCK TABLES `tinhlai` WRITE;
/*!40000 ALTER TABLE `tinhlai` DISABLE KEYS */;
/*!40000 ALTER TABLE `tinhlai` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2018-04-01 18:26:06
|
SELECT slug FROM clients
WHERE hash = ?
|
CREATE TABLE `articles` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) unsigned DEFAULT '0' COMMENT '0-no',
`thanks` int(11) unsigned DEFAULT '0',
`comments` int(11) unsigned DEFAULT '0',
`content` varchar(400) DEFAULT NULL,
`created_at` int(11) DEFAULT 0,
`updated_at` int(11) DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
create or replace procedure p_gencardlist(v_cardid IN t_card.cardid%TYPE,
v_makebatchno IN t_cardlist.batchno%TYPE) is
begin
begin
insert into t_cardlist
select a.cardasno,
v_makebatchno,
a.cardno,
a.cardphyid,
a.issueunit,
b.custname,
b.idtype,
b.idno,
b.birthday,
b.height,
b.sex,
b.tel,
b.mobile,
b.email,
b.unitname,
b.married,
b.education,
b.politics,
b.incomesrc,
b.country,
b.nation,
b.native,
b.domiciletype,
b.domicile,
b.livereason,
b.addr,
b.livedate,
b.arrivaldate,
c.photo,
0,
0,
to_char(sysdate, 'YYYYMMDDHH24MISS'),
''
from t_card a
left join t_customer b
on a.custid = b.custid
left join t_photo c
on a.custid = c.custid
where a.cardid = v_cardid; --and a.status=6;
end;
end p_gencardlist; |
--(모두 단일 행 함수를 이용하세요)
--1) 이름이 두 글자인 학생의 이름을 검색한다
SELECT *
FROM student
WHERE LENGTH(sname)=2;
--2) '공'씨 성을 가진 학생의 이름을 검색한다
SELECT *
FROM student
WHERE SUBSTR(sname,1,1)='공';
--3) 교수의 지위를 한글자로 검색한다(ex.조교수->조)
SELECT pno,pname,SUBSTR(orders,1,1) 지위
FROM professor;
--4) 일반 과목을 기초 과목으로 변경해서
-- 모든 과목을 검색한다(ex.일반화학->기초화학)
SELECT REPLACE(cname,'일반','기초') 과목
FROM course c;
--5) 만일 입력 실수로 student테이블의 sname컬럼에
-- 데이터가 입력될 때 문자열 마지막에 공백이 추가되었다면
-- 검색할 때 이를 제외하고 검색하는 SELECT문을 작성한다.
SELECT sno, TRIM(trailing ' ' from sname) 이름
FROM student;
|
-- criação das tabelas
CREATE TABLE cliente
( ID_CLIENTE NUMBER(5),
NOME VARCHAR2(40),
TELEFONE VARCHAR2(20),
ENDERECO VARCHAR2(100),
DATA_INCLUSAO DATE);
--criação da chave primária da tabela cliente
ALTER TABLE cliente ADD CONSTRAINT cliente_id_pk
PRIMARY KEY(ID_CLIENTE);
CREATE TABLE cliente_pf
( ID_CLIENTE NUMBER(5),
CPFVARCHAR2(15));
--criação da chave estrangeira do cliente pessoa Física
ALTER TABLE cliente_pf
ADD CONSTRAINT cliente_pf_fk
FOREIGN KEY(cliente_id)
REFERENCES cliente(ID_CLIENTE);
CREATE TABLE cliente_pj
( ID_CLIENTE NUMBER(5),
CNPJ VARCHAR2(15),
NIRE VARCHAR2(20),
RAZAO VARCHAR2(100));
--criação da chave estrangeira do cliente pessoa Jurídica
ALTER TABLE cliente_pj
ADD CONSTRAINT cliente_pj_fk
FOREIGN KEY(cliente_id)
REFERENCES cliente(ID_CLIENTE);
CREATE TABLE conta
( ID_CLIENTE NUMBER(5),
ID_CONTA NUMBER(5),
MOVIMENTACAO_CREDITO INTEGER,
MOVIMENTACAO_DEBITO INTEGER,
TOTAL_MOVIMENTACOES INTEGER,
TOTAL_MOVIMENTACOES INTEGER,
VALOR_MOVIMENTACOES FLOAT,
SALDO_INICIAL FLOAT,
SALDO_ATUAL FLOAT,
DATA_CRIACAO DATE,
ATIVA(5));
--criação da chave estrangeira da conta
ALTER TABLE conta
ADD CONSTRAINT conta_fk
FOREIGN KEY(cliente_id)
REFERENCES cliente(ID_CLIENTE);
|
DWD层之用户行为数据部分
1. 启动日志表
建表语句
------------------------------------------------------
drop table if exists dwd_start_log;
CREATE EXTERNAL TABLE dwd_start_log( --字段为示例数据中出现的字段
`mid_id` string,
`user_id` string,
`version_code` string,
`version_name` string,
`lang` string,
`source` string,
`os` string,
`area` string,
`model` string,
`brand` string,
`sdk_version` string,
`gmail` string,
`height_width` string,
`app_time` string,
`network` string,
`lng` string,
`lat` string,
`entry` string,
`open_ad_type` string,
`action` string,
`loading_time` string,
`detail` string,
`extend1` string
)
PARTITIONED BY (dt string) --以日期为分区
stored as parquet --存储格式为列式存储格式Parquet
location '/warehouse/gmall/dwd/dwd_start_log/' --指定存储目录
tblproperties ("parquet.compression"="lzo") --指定压缩格式为LZO
;
----------------------------------------------------
数据加载
----------------------------------------------------
insert overwrite table dwd_start_log –PARTITION (dt='2020-03-10') –-指定分区
select
get_json_object(line,'$.mid') mid_id, --使用Hive内置的JSON解析工具解析JSON字符串,获取字段值
get_json_object(line,'$.uid') user_id,
get_json_object(line,'$.vc') version_code,
get_json_object(line,'$.vn') version_name,
get_json_object(line,'$.l') lang,
get_json_object(line,'$.sr') source,
get_json_object(line,'$.os') os,
get_json_object(line,'$.ar') area,
get_json_object(line,'$.md') model,
get_json_object(line,'$.ba') brand,
get_json_object(line,'$.sv') sdk_version,
get_json_object(line,'$.g') gmail,
get_json_object(line,'$.hw') height_width,
get_json_object(line,'$.t') app_time,
get_json_object(line,'$.nw') network,
get_json_object(line,'$.ln') lng,
get_json_object(line,'$.la') lat,
get_json_object(line,'$.entry') entry,
get_json_object(line,'$.open_ad_type') open_ad_type,
get_json_object(line,'$.action') action,
get_json_object(line,'$.loading_time') loading_time,
get_json_object(line,'$.detail') detail,
get_json_object(line,'$.extend1') extend1
from ods_start_log --数据来源为ODS层的启动日志表
where dt='2020-03-10'; --指定数据日期
---------------------------------------------------
导入脚本 dwd_start_log.sh
---------------------------------------------------
#!/bin/bash
# 定义变量,方便后续修改
APP=gmall
hive=/opt/module/hive/bin/hive
# 如果输入了日期参数,则取输入参数作为日期值;如果没有输入日期参数,则取当前时间的前一天作为日期值
if [ -n "$1" ] ;then
do_date=$1
else
do_date=`date -d "-1 day" +%F`
fi
sql="
insert overwrite table "$APP".dwd_start_log
PARTITION (dt='$do_date')
select
get_json_object(line,'$.mid') mid_id,
get_json_object(line,'$.uid') user_id,
get_json_object(line,'$.vc') version_code,
get_json_object(line,'$.vn') version_name,
get_json_object(line,'$.l') lang,
get_json_object(line,'$.sr') source,
get_json_object(line,'$.os') os,
get_json_object(line,'$.ar') area,
get_json_object(line,'$.md') model,
get_json_object(line,'$.ba') brand,
get_json_object(line,'$.sv') sdk_version,
get_json_object(line,'$.g') gmail,
get_json_object(line,'$.hw') height_width,
get_json_object(line,'$.t') app_time,
get_json_object(line,'$.nw') network,
get_json_object(line,'$.ln') lng,
get_json_object(line,'$.la') lat,
get_json_object(line,'$.entry') entry,
get_json_object(line,'$.open_ad_type') open_ad_type,
get_json_object(line,'$.action') action,
get_json_object(line,'$.loading_time') loading_time,
get_json_object(line,'$.detail') detail,
get_json_object(line,'$.extend1') extend1
from "$APP".ods_start_log
where dt='$do_date';
"
$hive -e "$sql"
--------------------------------------------------
2. 用户行为事件基础明细表
建表语句
--------------------------------------------------
drop table if exists dwd_base_event_log;
CREATE EXTERNAL TABLE dwd_base_event_log(
`mid_id` string,
`user_id` string,
`version_code` string,
`version_name` string,
`lang` string,
`source` string,
`os` string,
`area` string,
`model` string,
`brand` string,
`sdk_version` string,
`gmail` string,
`height_width` string,
`app_time` string,
`network` string,
`lng` string,
`lat` string,
`event_name` string,
`event_json` string,
`server_time` string
)
PARTITIONED BY (`dt` string)
stored as parquet
location '/warehouse/gmall/dwd/dwd_base_event_log/'
TBLPROPERTIES('parquet.compression'='lzo');
----------------------------------------------------
创建永久函数
----------------------------------------------------
create function base_analizer as 'com.atguigu.udf.BaseFieldUDF' using jar 'hdfs://hadoop102:9000/user/hive/jars/hivefunction-1.0-SNAPSHOT.jar';
create function flat_analizer as 'com.atguigu.udtf.EventJsonUDTF' using jar 'hdfs://hadoop102:9000/user/hive/jars/hivefunction-1.0-SNAPSHOT.jar';
----------------------------------------------------
数据加载
----------------------------------------------------
insert overwrite table dwd_base_event_log partition(dt='2020-03-10')
select
base_analizer(line,'mid') as mid_id,
base_analizer(line,'uid') as user_id,
base_analizer(line,'vc') as version_code,
base_analizer(line,'vn') as version_name,
base_analizer(line,'l') as lang,
base_analizer(line,'sr') as source,
base_analizer(line,'os') as os,
base_analizer(line,'ar') as area,
base_analizer(line,'md') as model,
base_analizer(line,'ba') as brand,
base_analizer(line,'sv') as sdk_version,
base_analizer(line,'g') as gmail,
base_analizer(line,'hw') as height_width,
base_analizer(line,'t') as app_time,
base_analizer(line,'nw') as network,
base_analizer(line,'ln') as lng,
base_analizer(line,'la') as lat,
event_name,
event_json,
base_analizer(line,'st') as server_time
from ods_event_log lateral view flat_analizer(base_analizer(line,'et')) tmp_flat as event_name,event_json
where dt='2020-03-10' and base_analizer(line,'et')<>'';
-------------------------------------------------------
导入脚本 dwd_base_log.sh
-------------------------------------------------------
#!/bin/bash
# 定义变量,方便后续修改
APP=gmall
hive=/opt/module/hive/bin/hive
# 如果输入了日期参数,则取输入参数作为日期值;如果没输入日期参数,则取当前时间的前一天作为日期值
if [ -n "$1" ] ;then
do_date=$1
else
do_date=`date -d "-1 day" +%F`
fi
sql="
insert overwrite table "$APP".dwd_base_event_log partition(dt='$do_date')
select
"$APP".base_analizer(line,'mid') as mid_id,
"$APP".base_analizer(line,'uid') as user_id,
"$APP".base_analizer(line,'vc') as version_code,
"$APP".base_analizer(line,'vn') as version_name,
"$APP".base_analizer(line,'l') as lang,
"$APP".base_analizer(line,'sr') as source,
"$APP".base_analizer(line,'os') as os,
"$APP".base_analizer(line,'ar') as area,
"$APP".base_analizer(line,'md') as model,
"$APP".base_analizer(line,'ba') as brand,
"$APP".base_analizer(line,'sv') as sdk_version,
"$APP".base_analizer(line,'g') as gmail,
"$APP".base_analizer(line,'hw') as height_width,
"$APP".base_analizer(line,'t') as app_time,
"$APP".base_analizer(line,'nw') as network,
"$APP".base_analizer(line,'ln') as lng,
"$APP".base_analizer(line,'la') as lat,
event_name,
event_json,
"$APP".base_analizer(line,'st') as server_time
from "$APP".ods_event_log lateral view "$APP".flat_analizer("$APP".base_
analizer(line,'et')) tem_flat as event_name,event_json
where dt='$do_date' and "$APP".base_analizer(line,'et')<>'';
"
$hive -e "$sql"
----------------------------------------------------------
3. 用户行为事件分类表
商品点击表建表语句
----------------------------------------------------------
drop table if exists dwd_display_log;
CREATE EXTERNAL TABLE dwd_display_log(
`mid_id` string,
`user_id` string,
`version_code` string,
`version_name` string,
`lang` string,
`source` string,
`os` string,
`area` string,
`model` string,
`brand` string,
`sdk_version` string,
`gmail` string,
`height_width` string,
`app_time` string,
`network` string,
`lng` string,
`lat` string,
`action` string,
`goodsid` string,
`place` string,
`extend1` string,
`category` string,
`server_time` string
)
PARTITIONED BY (dt string)
location '/warehouse/gmall/dwd/dwd_display_log/';
----------------------------------------------------------
商品点击表数据加载
----------------------------------------------------------
insert overwrite table dwd_display_log
PARTITION (dt='2020-03-10')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.action') action,
get_json_object(event_json,'$.kv.goodsid') goodsid,
get_json_object(event_json,'$.kv.place') place,
get_json_object(event_json,'$.kv.extend1') extend1,
get_json_object(event_json,'$.kv.category') category,
server_time
from dwd_base_event_log
where dt='2020-03-10' and event_name='display';
-----------------------------------------------------------
商品详情页表建表语句
-----------------------------------------------------------
drop table if exists dwd_newsdetail_log;
CREATE EXTERNAL TABLE dwd_newsdetail_log(
`mid_id` string,
`user_id` string,
`version_code` string,
`version_name` string,
`lang` string,
`source` string,
`os` string,
`area` string,
`model` string,
`brand` string,
`sdk_version` string,
`gmail` string,
`height_width` string,
`app_time` string,
`network` string,
`lng` string,
`lat` string,
`entry` string,
`action` string,
`goodsid` string,
`showtype` string,
`news_staytime` string,
`loading_time` string,
`type1` string,
`category` string,
`server_time` string
)
PARTITIONED BY (dt string)
location '/warehouse/gmall/dwd/dwd_newsdetail_log/';
-------------------------------------------------------------
商品详情页表数据加载
-------------------------------------------------------------
insert overwrite table dwd_newsdetail_log PARTITION (dt='2020-03-10')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.entry') entry,
get_json_object(event_json,'$.kv.action') action,
get_json_object(event_json,'$.kv.goodsid') goodsid,
get_json_object(event_json,'$.kv.showtype') showtype,
get_json_object(event_json,'$.kv.news_staytime') news_staytime,
get_json_object(event_json,'$.kv.loading_time') loading_time,
get_json_object(event_json,'$.kv.type1') type1,
get_json_object(event_json,'$.kv.category') category,
server_time
from dwd_base_event_log
where dt='2020-03-10' and event_name='newsdetail';
--------------------------------------------------------------
商品列表页表建表语句
--------------------------------------------------------------
drop table if exists dwd_loading_log;
CREATE EXTERNAL TABLE dwd_loading_log(
`mid_id` string,
`user_id` string,
`version_code` string,
`version_name` string,
`lang` string,
`source` string,
`os` string,
`area` string,
`model` string,
`brand` string,
`sdk_version` string,
`gmail` string,
`height_width` string,
`app_time` string,
`network` string,
`lng` string,
`lat` string,
`action` string,
`loading_time` string,
`loading_way` string,
`extend1` string,
`extend2` string,
`type` string,
`type1` string,
`server_time` string
)
PARTITIONED BY (dt string)
location '/warehouse/gmall/dwd/dwd_loading_log/';
-------------------------------------------------------------
商品列表页表数据加载
-------------------------------------------------------------
insert overwrite table dwd_loading_log PARTITION (dt='2020-03-10')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.action') action,
get_json_object(event_json,'$.kv.loading_time') loading_time,
get_json_object(event_json,'$.kv.loading_way') loading_way,
get_json_object(event_json,'$.kv.extend1') extend1,
get_json_object(event_json,'$.kv.extend2') extend2,
get_json_object(event_json,'$.kv.type') type,
get_json_object(event_json,'$.kv.type1') type1,
server_time
from dwd_base_event_log
where dt='2020-03-10' and event_name='loading';
------------------------------------------------------------
广告表建表语句
------------------------------------------------------------
drop table if exists dwd_ad_log;
CREATE EXTERNAL TABLE dwd_ad_log(
`mid_id` string,
`user_id` string,
`version_code` string,
`version_name` string,
`lang` string,
`source` string,
`os` string,
`area` string,
`model` string,
`brand` string,
`sdk_version` string,
`gmail` string,
`height_width` string,
`app_time` string,
`network` string,
`lng` string,
`lat` string,
`entry` string,
`action` string,
`content` string,
`detail` string,
`ad_source` string,
`behavior` string,
`newstype` string,
`show_style` string,
`server_time` string
)
PARTITIONED BY (dt string)
location '/warehouse/gmall/dwd/dwd_ad_log/';
-------------------------------------------------------------
广告表数据加载
-------------------------------------------------------------
insert overwrite table dwd_ad_log PARTITION (dt='2020-03-10')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.entry') entry,
get_json_object(event_json,'$.kv.action') action,
get_json_object(event_json,'$.kv.content') content,
get_json_object(event_json,'$.kv.detail') detail,
get_json_object(event_json,'$.kv.source') ad_source,
get_json_object(event_json,'$.kv.behavior') behavior,
get_json_object(event_json,'$.kv.newstype') newstype,
get_json_object(event_json,'$.kv.show_style') show_style,
server_time
from dwd_base_event_log
where dt='2020-03-10' and event_name='ad';
-------------------------------------------------------------
消息通知表建表语句
-------------------------------------------------------------
drop table if exists dwd_notification_log;
CREATE EXTERNAL TABLE dwd_notification_log(
`mid_id` string,
`user_id` string,
`version_code` string,
`version_name` string,
`lang` string,
`source` string,
`os` string,
`area` string,
`model` string,
`brand` string,
`sdk_version` string,
`gmail` string,
`height_width` string,
`app_time` string,
`network` string,
`lng` string,
`lat` string,
`action` string,
`noti_type` string,
`ap_time` string,
`content` string,
`server_time` string
)
PARTITIONED BY (dt string)
location '/warehouse/gmall/dwd/dwd_notification_log/';
------------------------------------------------------------
消息通知表数据加载
------------------------------------------------------------
insert overwrite table dwd_notification_log
PARTITION (dt='2020-03-10')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.action') action,
get_json_object(event_json,'$.kv.noti_type') noti_type,
get_json_object(event_json,'$.kv.ap_time') ap_time,
get_json_object(event_json,'$.kv.content') content,
server_time
from dwd_base_event_log
where dt='2020-03-10' and event_name='notification';
-----------------------------------------------------------
用户后台活跃表建表语句
-----------------------------------------------------------
drop table if exists dwd_active_background_log;
CREATE EXTERNAL TABLE dwd_active_background_log(
`mid_id` string,
`user_id` string,
`version_code` string,
`version_name` string,
`lang` string,
`source` string,
`os` string,
`area` string,
`model` string,
`brand` string,
`sdk_version` string,
`gmail` string,
`height_width` string,
`app_time` string,
`network` string,
`lng` string,
`lat` string,
`active_source` string,
`server_time` string
)
PARTITIONED BY (dt string)
location '/warehouse/gmall/dwd/dwd_background_log/';
-----------------------------------------------------------
用户后台活跃表数据加载
-----------------------------------------------------------
insert overwrite table dwd_active_background_log
PARTITION (dt='2020-03-10')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.active_source') active_source,
server_time
from dwd_base_event_log
where dt='2020-03-10' and event_name='active_background';
------------------------------------------------------------
评价表建表语句
------------------------------------------------------------
drop table if exists dwd_comment_log;
CREATE EXTERNAL TABLE dwd_comment_log(
`mid_id` string,
`user_id` string,
`version_code` string,
`version_name` string,
`lang` string,
`source` string,
`os` string,
`area` string,
`model` string,
`brand` string,
`sdk_version` string,
`gmail` string,
`height_width` string,
`app_time` string,
`network` string,
`lng` string,
`lat` string,
`comment_id` int,
`userid` int,
`p_comment_id` int,
`content` string,
`addtime` string,
`other_id` int,
`praise_count` int,
`reply_count` int,
`server_time` string
)
PARTITIONED BY (dt string)
location '/warehouse/gmall/dwd/dwd_comment_log/';
------------------------------------------------------------
评价表数据加载
------------------------------------------------------------
insert overwrite table dwd_comment_log
PARTITION (dt='2020-03-10')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.comment_id') comment_id,
get_json_object(event_json,'$.kv.userid') userid,
get_json_object(event_json,'$.kv.p_comment_id') p_comment_id,
get_json_object(event_json,'$.kv.content') content,
get_json_object(event_json,'$.kv.addtime') addtime,
get_json_object(event_json,'$.kv.other_id') other_id,
get_json_object(event_json,'$.kv.praise_count') praise_count,
get_json_object(event_json,'$.kv.reply_count') reply_count,
server_time
from dwd_base_event_log
where dt='2020-03-10' and event_name='comment';
-------------------------------------------------------------
收藏表建表语句
-------------------------------------------------------------
drop table if exists dwd_favorites_log;
CREATE EXTERNAL TABLE dwd_favorites_log(
`mid_id` string,
`user_id` string,
`version_code` string,
`version_name` string,
`lang` string,
`source` string,
`os` string,
`area` string,
`model` string,
`brand` string,
`sdk_version` string,
`gmail` string,
`height_width` string,
`app_time` string,
`network` string,
`lng` string,
`lat` string,
`id` int,
`course_id` int,
`userid` int,
`add_time` string,
`server_time` string
)
PARTITIONED BY (dt string)
location '/warehouse/gmall/dwd/dwd_favorites_log/';
-------------------------------------------------------------
收藏表数据加载
-------------------------------------------------------------
insert overwrite table dwd_favorites_log
PARTITION (dt='2020-03-10')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.id') id,
get_json_object(event_json,'$.kv.course_id') course_id,
get_json_object(event_json,'$.kv.userid') userid,
get_json_object(event_json,'$.kv.add_time') add_time,
server_time
from dwd_base_event_log
where dt='2020-03-10' and event_name='favorites';
------------------------------------------------------------
点赞表建表语句
------------------------------------------------------------
drop table if exists dwd_praise_log;
CREATE EXTERNAL TABLE dwd_praise_log(
`mid_id` string,
`user_id` string,
`version_code` string,
`version_name` string,
`lang` string,
`source` string,
`os` string,
`area` string,
`model` string,
`brand` string,
`sdk_version` string,
`gmail` string,
`height_width` string,
`app_time` string,
`network` string,
`lng` string,
`lat` string,
`id` string,
`userid` string,
`target_id` string,
`type` string,
`add_time` string,
`server_time` string
)
PARTITIONED BY (dt string)
location '/warehouse/gmall/dwd/dwd_praise_log/';
------------------------------------------------------------
点赞表数据加载
------------------------------------------------------------
insert overwrite table dwd_praise_log
PARTITION (dt='2020-03-10')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.id') id,
get_json_object(event_json,'$.kv.userid') userid,
get_json_object(event_json,'$.kv.target_id') target_id,
get_json_object(event_json,'$.kv.type') type,
get_json_object(event_json,'$.kv.add_time') add_time,
server_time
from dwd_base_event_log
where dt='2020-03-10' and event_name='praise';
------------------------------------------------------------
错误日志表建表语句
------------------------------------------------------------
drop table if exists dwd_error_log;
CREATE EXTERNAL TABLE dwd_error_log(
`mid_id` string,
`user_id` string,
`version_code` string,
`version_name` string,
`lang` string,
`source` string,
`os` string,
`area` string,
`model` string,
`brand` string,
`sdk_version` string,
`gmail` string,
`height_width` string,
`app_time` string,
`network` string,
`lng` string,
`lat` string,
`errorBrief` string,
`errorDetail` string,
`server_time` string
)
PARTITIONED BY (dt string)
location '/warehouse/gmall/dwd/dwd_error_log/';
-----------------------------------------------------------
错误日志表数据加载
-----------------------------------------------------------
insert overwrite table dwd_error_log
PARTITION (dt='2020-03-10')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.errorBrief') errorBrief,
get_json_object(event_json,'$.kv.errorDetail') errorDetail,
server_time
from dwd_base_event_log
where dt='2020-03-10' and event_name='error';
-------------------------------------------------------------
用户行为事件分类表数据导入脚本 ods_to_dwd_event_log.sh
-------------------------------------------------------------
#!/bin/bash
# 定义变量,方便后续修改
APP=gmall
hive=/opt/module/hive/bin/hive
# 如果输入了日期参数,则取输入参数作为日期值;如果没输入日期参数,则取当前时间的前一天作为日期值
if [ -n "$1" ] ;then
do_date=$1
else
do_date=`date -d "-1 day" +%F`
fi
sql="
insert overwrite table "$APP".dwd_display_log
PARTITION (dt='$do_date')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.action') action,
get_json_object(event_json,'$.kv.goodsid') goodsid,
get_json_object(event_json,'$.kv.place') place,
get_json_object(event_json,'$.kv.extend1') extend1,
get_json_object(event_json,'$.kv.category') category,
server_time
from "$APP".dwd_base_event_log
where dt='$do_date' and event_name='display';
insert overwrite table "$APP".dwd_newsdetail_log
PARTITION (dt='$do_date')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.entry') entry,
get_json_object(event_json,'$.kv.action') action,
get_json_object(event_json,'$.kv.goodsid') goodsid,
get_json_object(event_json,'$.kv.showtype') showtype,
get_json_object(event_json,'$.kv.news_staytime') news_staytime,
get_json_object(event_json,'$.kv.loading_time') loading_time,
get_json_object(event_json,'$.kv.type1') type1,
get_json_object(event_json,'$.kv.category') category,
server_time
from "$APP".dwd_base_event_log
where dt='$do_date' and event_name='newsdetail';
insert overwrite table "$APP".dwd_loading_log
PARTITION (dt='$do_date')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.action') action,
get_json_object(event_json,'$.kv.loading_time') loading_time,
get_json_object(event_json,'$.kv.loading_way') loading_way,
get_json_object(event_json,'$.kv.extend1') extend1,
get_json_object(event_json,'$.kv.extend2') extend2,
get_json_object(event_json,'$.kv.type') type,
get_json_object(event_json,'$.kv.type1') type1,
server_time
from "$APP".dwd_base_event_log
where dt='$do_date' and event_name='loading';
insert overwrite table "$APP".dwd_ad_log
PARTITION (dt='$do_date')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.entry') entry,
get_json_object(event_json,'$.kv.action') action,
get_json_object(event_json,'$.kv.contentType') contentType,
get_json_object(event_json,'$.kv.displayMills') displayMills,
get_json_object(event_json,'$.kv.itemId') itemId,
get_json_object(event_json,'$.kv.activityId') activityId,
server_time
from "$APP".dwd_base_event_log
where dt='$do_date' and event_name='ad';
insert overwrite table "$APP".dwd_notification_log
PARTITION (dt='$do_date')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.action') action,
get_json_object(event_json,'$.kv.noti_type') noti_type,
get_json_object(event_json,'$.kv.ap_time') ap_time,
get_json_object(event_json,'$.kv.content') content,
server_time
from "$APP".dwd_base_event_log
where dt='$do_date' and event_name='notification';
insert overwrite table "$APP".dwd_active_background_log
PARTITION (dt='$do_date')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.active_source') active_source,
server_time
from "$APP".dwd_base_event_log
where dt='$do_date' and event_name='active_background';
insert overwrite table "$APP".dwd_comment_log
PARTITION (dt='$do_date')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.comment_id') comment_id,
get_json_object(event_json,'$.kv.userid') userid,
get_json_object(event_json,'$.kv.p_comment_id') p_comment_id,
get_json_object(event_json,'$.kv.content') content,
get_json_object(event_json,'$.kv.addtime') addtime,
get_json_object(event_json,'$.kv.other_id') other_id,
get_json_object(event_json,'$.kv.praise_count') praise_count,
get_json_object(event_json,'$.kv.reply_count') reply_count,
server_time
from "$APP".dwd_base_event_log
where dt='$do_date' and event_name='comment';
insert overwrite table "$APP".dwd_favorites_log
PARTITION (dt='$do_date')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.id') id,
get_json_object(event_json,'$.kv.course_id') course_id,
get_json_object(event_json,'$.kv.userid') userid,
get_json_object(event_json,'$.kv.add_time') add_time,
server_time
from "$APP".dwd_base_event_log
where dt='$do_date' and event_name='favorites';
insert overwrite table "$APP".dwd_praise_log
PARTITION (dt='$do_date')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.id') id,
get_json_object(event_json,'$.kv.userid') userid,
get_json_object(event_json,'$.kv.target_id') target_id,
get_json_object(event_json,'$.kv.type') type,
get_json_object(event_json,'$.kv.add_time') add_time,
server_time
from "$APP".dwd_base_event_log
where dt='$do_date' and event_name='praise';
insert overwrite table "$APP".dwd_error_log
PARTITION (dt='$do_date')
select
mid_id,
user_id,
version_code,
version_name,
lang,
source,
os,
area,
model,
brand,
sdk_version,
gmail,
height_width,
app_time,
network,
lng,
lat,
get_json_object(event_json,'$.kv.errorBrief') errorBrief,
get_json_object(event_json,'$.kv.errorDetail') errorDetail,
server_time
from "$APP".dwd_base_event_log
where dt='$do_date' and event_name='error';
"
$hive -e "$sql"
--------------------------------------------------------------
|
-- Created by Vertabelo (http://vertabelo.com)
-- Last modification date: 2021-01-04 22:23:27.662
-- tables
-- Table: Adresy
CREATE TABLE Adresy (
mesto nvarchar(100) NOT NULL,
ulice nvarchar(100) NOT NULL,
psc int NOT NULL,
id_adresy int NOT NULL IDENTITY,
CONSTRAINT Adresy_pk PRIMARY KEY (id_adresy)
);
-- Table: Navstevy
CREATE TABLE Navstevy (
pacienti_rodne_cislo nvarchar(10) NOT NULL,
id_zamestnanec int NOT NULL,
id_ordinace int NOT NULL,
datum datetime NOT NULL,
popis nvarchar(500) NOT NULL,
CONSTRAINT PK_Navstevy PRIMARY KEY (id_zamestnanec,id_ordinace,pacienti_rodne_cislo,datum)
);
-- Table: Ordinace
CREATE TABLE Ordinace (
id_ordinace int NOT NULL IDENTITY,
nazev nvarchar(100) NOT NULL,
id_poliklinika int NOT NULL,
CONSTRAINT Ordinace_pk PRIMARY KEY (id_ordinace)
);
-- Table: Pacient_Ordinace
CREATE TABLE Pacient_Ordinace (
id_ordinace int NOT NULL,
pacienti_rodne_cislo nvarchar(10) NOT NULL,
CONSTRAINT Pacient_Ordinace_pk PRIMARY KEY (id_ordinace,pacienti_rodne_cislo)
);
-- Table: Pacienti
CREATE TABLE Pacienti (
rodne_cislo nvarchar(10) NOT NULL,
id_adresy int NOT NULL,
jmeno nvarchar(100) NOT NULL,
CONSTRAINT Pacienti_pk PRIMARY KEY (rodne_cislo)
);
-- Table: Polikliniky
CREATE TABLE Polikliniky (
id_poliklinika int NOT NULL IDENTITY,
id_adresy int NOT NULL,
CONSTRAINT Polikliniky_pk PRIMARY KEY (id_poliklinika)
);
-- Table: SeznamPozic
CREATE TABLE SeznamPozic (
id_pozice int NOT NULL IDENTITY,
nazev nvarchar(100) NOT NULL,
CONSTRAINT SeznamPozic_pk PRIMARY KEY (id_pozice)
);
-- Table: Zamestnanci
CREATE TABLE Zamestnanci (
id_zamestnanec int NOT NULL IDENTITY,
jmeno nvarchar(100) NOT NULL,
titul nvarchar(10) NULL,
id_adresy int NOT NULL,
id_pozice int NOT NULL,
CONSTRAINT Zamestnanci_pk PRIMARY KEY (id_zamestnanec)
);
-- Table: Zamestnanec_Ordinace
CREATE TABLE Zamestnanec_Ordinace (
id_zamestnanec int NOT NULL,
id_ordinace int NOT NULL,
od datetime NOT NULL,
do datetime NULL,
CONSTRAINT Zamestnanec_Ordinace_pk PRIMARY KEY (id_zamestnanec,id_ordinace)
);
-- foreign keys
-- Reference: Navstevy_Ordinace (table: Navstevy)
ALTER TABLE Navstevy ADD CONSTRAINT Navstevy_Ordinace
FOREIGN KEY (id_ordinace)
REFERENCES Ordinace (id_ordinace);
-- Reference: Navstevy_Pacienti (table: Navstevy)
ALTER TABLE Navstevy ADD CONSTRAINT Navstevy_Pacienti
FOREIGN KEY (pacienti_rodne_cislo)
REFERENCES Pacienti (rodne_cislo);
-- Reference: Navstevy_Zamestnanci (table: Navstevy)
ALTER TABLE Navstevy ADD CONSTRAINT Navstevy_Zamestnanci
FOREIGN KEY (id_zamestnanec)
REFERENCES Zamestnanci (id_zamestnanec);
-- Reference: Ordinace_Polikliniky (table: Ordinace)
ALTER TABLE Ordinace ADD CONSTRAINT Ordinace_Polikliniky
FOREIGN KEY (id_poliklinika)
REFERENCES Polikliniky (id_poliklinika)
ON DELETE CASCADE;
-- Reference: Pacient_Ordinace_Ordinace (table: Pacient_Ordinace)
ALTER TABLE Pacient_Ordinace ADD CONSTRAINT Pacient_Ordinace_Ordinace
FOREIGN KEY (id_ordinace)
REFERENCES Ordinace (id_ordinace)
ON DELETE CASCADE;
-- Reference: Pacient_Ordinace_Pacienti (table: Pacient_Ordinace)
ALTER TABLE Pacient_Ordinace ADD CONSTRAINT Pacient_Ordinace_Pacienti
FOREIGN KEY (pacienti_rodne_cislo)
REFERENCES Pacienti (rodne_cislo)
ON DELETE CASCADE;
-- Reference: Pacienti_Adresy (table: Pacienti)
ALTER TABLE Pacienti ADD CONSTRAINT Pacienti_Adresy
FOREIGN KEY (id_adresy)
REFERENCES Adresy (id_adresy);
-- Reference: Polikliniky_Adresy (table: Polikliniky)
ALTER TABLE Polikliniky ADD CONSTRAINT Polikliniky_Adresy
FOREIGN KEY (id_adresy)
REFERENCES Adresy (id_adresy);
-- Reference: Table_15_Ordinace (table: Zamestnanec_Ordinace)
ALTER TABLE Zamestnanec_Ordinace ADD CONSTRAINT Table_15_Ordinace
FOREIGN KEY (id_ordinace)
REFERENCES Ordinace (id_ordinace)
ON DELETE CASCADE;
-- Reference: Table_15_Zamestnanci (table: Zamestnanec_Ordinace)
ALTER TABLE Zamestnanec_Ordinace ADD CONSTRAINT Table_15_Zamestnanci
FOREIGN KEY (id_zamestnanec)
REFERENCES Zamestnanci (id_zamestnanec);
-- Reference: Zamestnanci_Adresy (table: Zamestnanci)
ALTER TABLE Zamestnanci ADD CONSTRAINT Zamestnanci_Adresy
FOREIGN KEY (id_adresy)
REFERENCES Adresy (id_adresy);
-- Reference: Zamestnanci_SeznamPozic (table: Zamestnanci)
ALTER TABLE Zamestnanci ADD CONSTRAINT Zamestnanci_SeznamPozic
FOREIGN KEY (id_pozice)
REFERENCES SeznamPozic (id_pozice);
-- End of file.
|
USE codeup_test_db;
SELECT name FROM albums where artist = 'Pink Floyd';
SELECT release_date FROM albums where name = 'Rumours';
SELECT genre FROM albums where artist = 'Eagles';
SELECT name FROM albums where release_date <= 1977 AND release_date >= 1970;
SELECT artist FROM albums where sales >= 44;
SELECT artist FROM albums where genre LIKE '%Rock%'; |
-- TITLE1:
-- TITLE2:Displaying Supplemental Logging Enabled by PREPARE_GLOBAL_INSTANTIATION
-- DESC:
COLUMN log_pk HEADING 'Primary Key|Supplemental|Logging' FORMAT A12
COLUMN log_fk HEADING 'Foreign Key|Supplemental|Logging' FORMAT A12
COLUMN log_ui HEADING 'Unique|Supplemental|Logging' FORMAT A12
COLUMN log_all HEADING 'All Columns|Supplemental|Logging' FORMAT A12
SELECT SUPPLEMENTAL_LOG_DATA_PK log_pk,
SUPPLEMENTAL_LOG_DATA_FK log_fk,
SUPPLEMENTAL_LOG_DATA_UI log_ui,
SUPPLEMENTAL_LOG_DATA_ALL log_all
FROM DBA_CAPTURE_PREPARED_DATABASE;
|
-- --------------------------------------------------------
-- Host: 127.0.0.1
-- Server version: 5.5.35-log - MySQL Community Server (GPL)
-- Server OS: Win32
-- HeidiSQL Version: 8.2.0.4690
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Dumping structure for table delphinpro_wt.cd_builds
CREATE TABLE IF NOT EXISTS `cd_builds` (
`worldId` int(10) unsigned NOT NULL,
`buildId` int(10) unsigned NOT NULL,
`title` varchar(50) NOT NULL,
`buildType` tinyint(3) unsigned NOT NULL,
`bt0` float unsigned NOT NULL,
`bt1` float unsigned NOT NULL,
`bt2` float unsigned NOT NULL,
`bt3` float unsigned NOT NULL,
`eff0` float unsigned NOT NULL,
`eff1` float unsigned NOT NULL,
`eff2` float unsigned NOT NULL,
`eff3` float unsigned NOT NULL,
`ug0` float unsigned NOT NULL,
`ug1` float unsigned NOT NULL,
`ug2` float unsigned NOT NULL,
`ug3` float unsigned NOT NULL,
`cost` varchar(255) NOT NULL,
PRIMARY KEY (`worldId`,`buildId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.cd_resource
CREATE TABLE IF NOT EXISTS `cd_resource` (
`worldId` int(10) unsigned NOT NULL,
`id` int(10) unsigned NOT NULL,
`title` varchar(50) NOT NULL,
`prodType` tinyint(3) unsigned NOT NULL,
`type` tinyint(3) unsigned NOT NULL,
PRIMARY KEY (`worldId`,`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.cd_science
CREATE TABLE IF NOT EXISTS `cd_science` (
`worldId` int(3) unsigned NOT NULL,
`id` int(3) unsigned NOT NULL,
`title` varchar(25) NOT NULL,
`cost` int(10) unsigned NOT NULL,
`need` varchar(50) NOT NULL,
`takes` varchar(50) NOT NULL,
`builds` varchar(255) NOT NULL,
`units` varchar(50) NOT NULL,
`bonuses` varchar(50) NOT NULL,
PRIMARY KEY (`id`,`worldId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.cd_units
CREATE TABLE IF NOT EXISTS `cd_units` (
`worldId` int(10) unsigned NOT NULL,
`unitId` int(10) unsigned NOT NULL,
`title` varchar(50) NOT NULL,
`ability` int(10) unsigned NOT NULL,
`airDamage` int(10) unsigned NOT NULL,
`capacity` int(10) unsigned NOT NULL,
`damage` int(10) unsigned NOT NULL,
`unitGroup` tinyint(3) unsigned NOT NULL,
`health` tinyint(3) unsigned NOT NULL,
`popCost` tinyint(3) unsigned NOT NULL,
`race` tinyint(3) unsigned NOT NULL,
`target` tinyint(3) NOT NULL,
`trainTime` int(10) unsigned NOT NULL,
`unitType` tinyint(3) NOT NULL,
`speed` tinyint(3) unsigned NOT NULL,
`cost` varchar(255) NOT NULL DEFAULT '[]',
`pay` varchar(255) NOT NULL DEFAULT '[]',
PRIMARY KEY (`unitId`,`worldId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.invites
CREATE TABLE IF NOT EXISTS `invites` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`invite` varchar(32) NOT NULL,
`activated` int(11) NOT NULL DEFAULT '0',
`from_user` int(11) DEFAULT NULL,
`to_user` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `INVITE_UNIQUE` (`invite`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.menus
CREATE TABLE IF NOT EXISTS `menus` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.menu_items
CREATE TABLE IF NOT EXISTS `menu_items` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`menu_id` int(10) unsigned NOT NULL,
`parent_id` int(10) unsigned NOT NULL DEFAULT '0',
`title` varchar(50) NOT NULL,
`target` varchar(50) NOT NULL,
`alias` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.profiles
CREATE TABLE IF NOT EXISTS `profiles` (
`user_id` int(10) unsigned NOT NULL,
`player_id` int(10) unsigned NOT NULL,
`country_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `player_id` (`player_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.st_countries
CREATE TABLE IF NOT EXISTS `st_countries` (
`worldId` smallint(5) unsigned NOT NULL,
`countryId` smallint(5) unsigned NOT NULL,
`countryTitle` varchar(25) DEFAULT NULL,
`countryFlag` varchar(25) DEFAULT NULL,
`created` date DEFAULT NULL,
`deleted` date DEFAULT NULL,
`existsCountry` tinyint(1) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`countryId`,`worldId`),
KEY `existsCountry` (`existsCountry`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.st_countries_dyn
CREATE TABLE IF NOT EXISTS `st_countries_dyn` (
`worldId` smallint(5) unsigned NOT NULL,
`countryId` smallint(5) unsigned NOT NULL,
`stateDate` date NOT NULL,
`countryPop` int(10) unsigned NOT NULL DEFAULT '0',
`countryPlayers` tinyint(10) unsigned NOT NULL DEFAULT '0',
`countryTowns` smallint(10) unsigned NOT NULL DEFAULT '0',
`deltaPopPerDay` int(10) DEFAULT NULL,
`deltaPopPerWeek` int(10) DEFAULT NULL,
`deltaPopPerMonth` int(10) DEFAULT NULL,
`deltaPlayersPerDay` tinyint(10) DEFAULT NULL,
`deltaPlayersPerWeek` tinyint(10) DEFAULT NULL,
`deltaPlayersPerMonth` tinyint(10) DEFAULT NULL,
`deltaTownsPerDay` smallint(10) DEFAULT NULL,
`deltaTownsPerWeek` smallint(10) DEFAULT NULL,
`deltaTownsPerMonth` smallint(10) DEFAULT NULL,
PRIMARY KEY (`worldId`,`countryId`,`stateDate`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.st_events
CREATE TABLE IF NOT EXISTS `st_events` (
`worldId` smallint(10) NOT NULL,
`stateDate` date NOT NULL,
`eventId` tinyint(10) NOT NULL,
`playerId` int(10) DEFAULT NULL,
`townId` int(10) DEFAULT NULL,
`wonderId` int(10) DEFAULT NULL,
`countryId` int(10) DEFAULT NULL,
`countryIdOld` int(10) DEFAULT NULL,
`playerName` varchar(25) DEFAULT NULL,
`townTitle` varchar(25) DEFAULT NULL,
`townTitleOld` varchar(25) DEFAULT NULL,
`countryTitle` varchar(25) DEFAULT NULL,
`countryTitleOld` varchar(25) DEFAULT NULL,
`countryFlag` varchar(25) DEFAULT NULL,
`countryFlagOld` varchar(25) DEFAULT NULL,
KEY `stateDate` (`stateDate`),
KEY `worldId` (`worldId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.st_players
CREATE TABLE IF NOT EXISTS `st_players` (
`worldId` smallint(10) unsigned NOT NULL,
`playerId` mediumint(11) unsigned NOT NULL,
`playerName` varchar(25) NOT NULL,
`playerRace` tinyint(1) unsigned NOT NULL DEFAULT '0',
`playerSex` tinyint(1) unsigned NOT NULL DEFAULT '0',
`countryId` smallint(11) unsigned NOT NULL DEFAULT '0',
`created` date DEFAULT NULL,
`deleted` date DEFAULT NULL,
`active` tinyint(3) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`playerId`,`worldId`),
KEY `countryId` (`countryId`),
KEY `existsPlayer` (`active`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.st_players_dyn
CREATE TABLE IF NOT EXISTS `st_players_dyn` (
`worldId` smallint(10) unsigned NOT NULL,
`playerId` mediumint(10) unsigned NOT NULL,
`stateDate` date NOT NULL,
`countryId` smallint(10) unsigned NOT NULL,
`playerPop` mediumint(10) DEFAULT NULL,
`playerTowns` tinyint(3) unsigned DEFAULT NULL,
`playerRatingWar` int(10) DEFAULT NULL,
`playerRatingScience` int(10) DEFAULT NULL,
`playerRatingProd` int(10) DEFAULT NULL,
`deltaPopPerDay` mediumint(10) DEFAULT NULL,
`deltaPopPerWeek` mediumint(10) DEFAULT NULL,
`deltaPopPerMonth` mediumint(10) DEFAULT NULL,
`deltaTownsPerDay` tinyint(3) DEFAULT NULL,
`deltaTownsPerWeek` tinyint(3) DEFAULT NULL,
`deltaTownsPerMonth` tinyint(3) DEFAULT NULL,
PRIMARY KEY (`worldId`,`playerId`,`stateDate`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.st_towns
CREATE TABLE IF NOT EXISTS `st_towns` (
`worldId` smallint(5) unsigned NOT NULL,
`townId` mediumint(6) unsigned NOT NULL,
`townTitle` varchar(50) DEFAULT NULL,
`playerId` mediumint(6) unsigned NOT NULL,
`createDate` date DEFAULT NULL,
`lostDate` date DEFAULT NULL,
`destroyDate` date DEFAULT NULL,
`isLost` tinyint(1) unsigned NOT NULL DEFAULT '0',
`isDestroy` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`townId`,`worldId`),
KEY `playerId` (`playerId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.st_towns_dyn
CREATE TABLE IF NOT EXISTS `st_towns_dyn` (
`worldId` smallint(5) unsigned NOT NULL,
`stateDate` date NOT NULL,
`townId` mediumint(6) unsigned NOT NULL,
`townPop` mediumint(10) DEFAULT NULL,
`playerId` mediumint(10) unsigned NOT NULL DEFAULT '0',
`deltaPerDay` mediumint(10) DEFAULT NULL,
`deltaPerWeek` mediumint(10) DEFAULT NULL,
`deltaPerMonth` mediumint(10) DEFAULT NULL,
`wonderId` smallint(5) unsigned NOT NULL DEFAULT '0',
`wonderLevel` tinyint(3) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`worldId`,`stateDate`,`townId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.supply
CREATE TABLE IF NOT EXISTS `supply` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`parent_id` int(10) unsigned NOT NULL DEFAULT '0',
`stream` tinyint(3) unsigned NOT NULL DEFAULT '0',
`player_id` int(10) unsigned NOT NULL,
`town_id` int(10) unsigned NOT NULL,
`target` tinyint(3) unsigned NOT NULL DEFAULT '0',
`date_open` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`closed` tinyint(3) unsigned NOT NULL DEFAULT '0',
`r1` int(3) unsigned NOT NULL DEFAULT '0',
`r2` int(3) unsigned NOT NULL DEFAULT '0',
`r3` int(3) unsigned NOT NULL DEFAULT '0',
`r4` int(3) unsigned NOT NULL DEFAULT '0',
`r5` int(3) unsigned NOT NULL DEFAULT '0',
`r6` int(3) unsigned NOT NULL DEFAULT '0',
`r7` int(3) unsigned NOT NULL DEFAULT '0',
`r8` int(3) unsigned NOT NULL DEFAULT '0',
`r9` int(3) unsigned NOT NULL DEFAULT '0',
`r10` int(3) unsigned NOT NULL DEFAULT '0',
`r11` int(3) unsigned NOT NULL DEFAULT '0',
`r12` int(3) unsigned NOT NULL DEFAULT '0',
`r13` int(3) unsigned NOT NULL DEFAULT '0',
`r14` int(3) unsigned NOT NULL DEFAULT '0',
`r15` int(3) unsigned NOT NULL DEFAULT '0',
`r16` int(3) unsigned NOT NULL DEFAULT '0',
`r17` int(3) unsigned NOT NULL DEFAULT '0',
`r18` int(3) unsigned NOT NULL DEFAULT '0',
`r19` int(3) unsigned NOT NULL DEFAULT '0',
`r20` int(3) unsigned NOT NULL DEFAULT '0',
`r21` int(3) unsigned NOT NULL DEFAULT '0',
`r22` int(3) unsigned NOT NULL DEFAULT '0',
`notes` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.tiles
CREATE TABLE IF NOT EXISTS `tiles` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`x` int(11) NOT NULL,
`y` int(11) NOT NULL,
`climate` int(11) NOT NULL,
`relief` int(11) NOT NULL,
`deposit` int(11) NOT NULL,
`wonder` int(11) NOT NULL,
`ecology` int(11) NOT NULL,
`rid` int(11) unsigned NOT NULL,
`road` int(11) unsigned NOT NULL,
`town_id` int(11) NOT NULL,
`player_id` int(11) NOT NULL,
`country_id` int(11) NOT NULL,
`diplomacy` int(11) NOT NULL,
`town_level` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `KEY_RID` (`rid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.users
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`login` varchar(32) NOT NULL,
`email` varchar(32) NOT NULL,
`password` varchar(32) NOT NULL,
`register` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`lastVisit` timestamp NULL DEFAULT NULL,
`sex` int(11) NOT NULL DEFAULT '0',
`status` int(11) NOT NULL DEFAULT '0',
`group` int(11) NOT NULL DEFAULT '0',
`rights` int(11) NOT NULL DEFAULT '0',
`uid` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `login` (`login`,`email`),
UNIQUE KEY `uid` (`uid`),
KEY `password` (`password`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.wt_armylog
CREATE TABLE IF NOT EXISTS `wt_armylog` (
`id` varchar(32) NOT NULL,
`world_country` enum('EN','RU') NOT NULL,
`world_id` int(10) unsigned NOT NULL,
`generate_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`report_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`options` varchar(50) DEFAULT '[]',
`verified` int(1) DEFAULT NULL,
`log_data` text NOT NULL,
UNIQUE KEY `id` (`id`),
KEY `world_country_world_id` (`world_country`,`world_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.wt_reports_science
CREATE TABLE IF NOT EXISTS `wt_reports_science` (
`id` varchar(50) NOT NULL,
`worldId` smallint(5) DEFAULT NULL,
`worldSign` varchar(4) DEFAULT NULL,
`worldTitle` varchar(25) DEFAULT NULL,
`generateTime` datetime DEFAULT NULL,
`domain` varchar(50) DEFAULT NULL,
`playerId` int(11) DEFAULT NULL,
`playerTitle` varchar(25) DEFAULT NULL,
`countryId` int(11) DEFAULT NULL,
`countryTitle` varchar(25) DEFAULT NULL,
`countryFlag` varchar(50) DEFAULT NULL,
`scCurrent` varchar(255) DEFAULT NULL,
`scKnown` varchar(500) DEFAULT NULL,
`scStarted` varchar(500) DEFAULT NULL,
`scNext` int(11) DEFAULT NULL,
`investedTotal` int(10) DEFAULT NULL,
`markupTotal` int(10) DEFAULT NULL,
`markupNext` int(10) DEFAULT NULL,
`countTotal` int(10) DEFAULT NULL,
`validKey` varchar(32) DEFAULT NULL,
`verified` tinyint(3) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `playerId` (`playerId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.wt_reports_war
CREATE TABLE IF NOT EXISTS `wt_reports_war` (
`id` varchar(32) NOT NULL,
`worldId` smallint(5) DEFAULT NULL,
`worldSign` varchar(4) DEFAULT NULL,
`worldTitle` varchar(25) DEFAULT NULL,
`generateTime` datetime DEFAULT NULL,
`reportTime` datetime DEFAULT NULL,
`domain` varchar(50) DEFAULT NULL,
`owner` int(10) unsigned DEFAULT NULL,
`spy` tinyint(3) unsigned DEFAULT NULL,
`aggressorId` int(10) unsigned DEFAULT NULL,
`aggressorTownId` int(10) unsigned DEFAULT NULL,
`aggressorCountryId` int(10) unsigned DEFAULT NULL,
`defendingId` int(10) unsigned DEFAULT NULL,
`defendingTownId` int(10) unsigned DEFAULT NULL,
`defendingCountryId` int(10) unsigned DEFAULT NULL,
`private` tinyint(3) unsigned DEFAULT NULL,
`validKey` varchar(32) DEFAULT NULL,
`verified` tinyint(3) unsigned DEFAULT '0',
`report` text,
PRIMARY KEY (`id`),
KEY `owner` (`owner`),
KEY `generateTime` (`generateTime`),
KEY `worldId` (`worldId`),
KEY `private` (`private`),
KEY `verified` (`verified`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
-- Dumping structure for table delphinpro_wt.wt_worlds
CREATE TABLE IF NOT EXISTS `wt_worlds` (
`id` int(10) unsigned NOT NULL,
`title` varchar(50) NOT NULL,
`sign` varchar(5) NOT NULL,
`started` datetime DEFAULT NULL,
`canReg` tinyint(1) DEFAULT '0',
`active` tinyint(1) DEFAULT '0',
`statistic` tinyint(1) DEFAULT '0',
`loadStat` datetime DEFAULT NULL,
`updateStat` datetime DEFAULT NULL,
`updateConst` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Data exporting was unselected.
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
|
CREATE PROCEDURE sp_get_Invoice_Cancel (@CustomerID NVARCHAR(15),
@FromDate DATETIME, @ToDate DATETIME, @FLAG int = 0)
AS
SELECT InvoiceAbstract.CustomerID AS "CustomerID", Company_Name, InvoiceID, InvoiceDate,
NetValue, InvoiceType, DocumentID, ISNULL(Status, 0), Balance, invoicereference,
DocReference,DocSerialType,isnull(GSTFullDocID, '') as GSTFullDocID
FROM InvoiceAbstract, Customer
WHERE InvoiceType in (1,3,4)
--AND (InvoiceAbstract.Status & 128) = 0
AND InvoiceAbstract.CustomerID = Customer.CustomerID
AND InvoiceAbstract.CustomerID like @CustomerID
AND InvoiceDate BETWEEN @FromDate AND @ToDate
--AND NetValue = ISNULL(Balance, 0)
AND (InvoiceAbstract.Status & @FLAG) = 0
AND (InvoiceAbstract.Status & 1024) = 0
ORDER BY InvoiceAbstract.CustomerID
|
-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Máy chủ: 127.0.0.1
-- Thời gian đã tạo: Th10 10, 2017 lúc 03:35 PM
-- Phiên bản máy phục vụ: 10.1.25-MariaDB
-- Phiên bản PHP: 7.1.7
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Cơ sở dữ liệu: `test`
--
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `user`
--
CREATE TABLE `user` (
`user_id` bigint(20) NOT NULL,
`user_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`user_password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`user_email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`fisrt_name` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Đang đổ dữ liệu cho bảng `user`
--
INSERT INTO `user` (`user_id`, `user_name`, `user_password`, `user_email`, `fisrt_name`, `last_name`, `create_date`) VALUES
(18, 'sach2', '$2a$10$yjGBaZBihz.bwcIOXsAjf.lTu2bXJYx4i1w7jKOXjW1HtAatVX79a', 'sach@gmail.com', 'Sách', 'Trần', '2017-09-30 13:14:54'),
(19, 'sach23', '$2a$10$9cTpU3Xlh2aLSYxQEOosWeF9LmTxUJp5Vip78rMjVdm9S7hz2BYs6', 'sach@gmail.com', 'Sách', 'Trần', '2017-09-30 13:39:00'),
(20, 'qqqqq', '$2a$10$9cTpU3Xlh2aLSYxQEOosWeF9LmTxUJp5Vip78rMjVdm9S7hz2BYs6', 'ẻ', 'ưẻw', 'ưẻ', '2017-09-30 13:40:01'),
(21, '12321', '$2a$10$sf3c7HXdwAtdP8vUAJY1V.cbAqQ8fRVqBAZx9XUJGXXAjwoBuxu5q', 'qư', 'qưeq', 'qưe', '2017-09-30 13:40:47'),
(22, '123213', '$2a$10$sf3c7HXdwAtdP8vUAJY1V.cbAqQ8fRVqBAZx9XUJGXXAjwoBuxu5q', 'qư', 'qưeq', 'qưe', '2017-09-30 13:40:58'),
(23, '1232131', '$2a$10$W6rCxOg90pUROJyx.oikUeXBbemHFy3Dc.l3RKQUl6xbNJjokohmW', 'qư', 'qưeq', 'qưe', '2017-09-30 13:41:13'),
(24, '123', '$2a$10$0iukdH3m0YR1dBfXZToXUeHsGqBNQXZIJBGNlc/nlbD/Qr02MitkW', 'ửẻ', 'qưeqưeq', 'qưewqe', '2017-09-30 13:52:35'),
(25, '1233', '$2a$10$wH8R/fvzT1YwIA0AMtg2j.9f0W/fKGMmGDGqm1qKSmdJHEssEXOFG', '123', '123213', '123', '2017-09-30 13:54:19'),
(27, '4443', '$2a$10$J/.NqYMmAJB5ZtjcYxpvaeAetqZ1hW/XQzTG2SIVWtsbJ8liTJ3pC', 'qư', 'qưe', 'qưe', '2017-09-30 14:08:06'),
(28, '1234', '$2a$10$Prkwi4n5iDEUTOwBg6QF8O/TzhIGKzuCFOfy3iip13puNQE/ok83e', 'qwe@gmail.com', 'qwe', 'werwer', '2017-09-30 14:19:11'),
(29, 'thang', '$2a$10$BvakOyxrh6/2Ge7noIEdE.vSl.CKU4PttxzHbvflFpj7OXt76aLXq', 'undefined', 'Lục', 'Thắng', '2017-09-30 14:30:17'),
(30, 'thanh', '$2a$10$2xtzidNwlRoRunBxrVv4rOove13uQhYfDnbiwm5Cp/JVCNpN9i53u', 'aqq@gmail.com', 'Nguyễn', 'Thành', '2017-09-30 14:43:03'),
(31, 'thien', '$2a$10$u31JbptXf5ikrmo0nh48L.u4orbzaJRRRR6Xxh.gtvX.3cnlhKziu', 'thien@gmail.com', 'thien', 'tran', '2017-10-12 15:34:24'),
(32, 'thang12', '$2a$10$2xtzidNwlRoRunBxrVv4rOove13uQhYfDnbiwm5Cp/JVCNpN9i53u', 'ádlă@gmail.com', 'Thắng', 'Lục', '2017-11-09 16:16:07'),
(33, 'thien123', '$2a$10$2xtzidNwlRoRunBxrVv4rOove13uQhYfDnbiwm5Cp/JVCNpN9i53u', 'qwe@gmail.com', 'thang', 'luc', '2017-11-10 18:00:15');
--
-- Chỉ mục cho các bảng đã đổ
--
--
-- Chỉ mục cho bảng `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`user_id`);
--
-- AUTO_INCREMENT cho các bảng đã đổ
--
--
-- AUTO_INCREMENT cho bảng `user`
--
ALTER TABLE `user`
MODIFY `user_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=34;COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
DROP TABLE ed_fmtcd_sql
DROP TABLE ed_cvtfl_sql
DROP TABLE ed_fmtce_sql
DROP TABLE ed_fmtcf_sql
DROP TABLE ed_fmtch_sql
DROP TABLE ed_fmtcm_sql
DROP TABLE ed_fmtde_sql
DROP TABLE ed_fmtdf_sql
DROP TABLE ed_fmte2_sql
DROP TABLE ed_fmted_sql
DROP TABLE ed_fmtef_sql
DROP TABLE ed_fmtem_sql
DROP TABLE ed_fmtfd_sql
DROP TABLE ed_fmtfx_sql
DROP TABLE ed_fmti1_sql
DROP TABLE ed_fmti2_sql
DROP TABLE ed_fmtlt_sql
DROP TABLE ed_fmtsi_sql
DROP TABLE ed_fmtsn_sql
DROP TABLE ed_fmtxa_sql
DROP TABLE ed_fmtxx_sql
DROP TABLE ed_scrfl_sql
DROP TABLE ed_tmp02_sql
DROP TABLE ed_tmp03_sql
DROP TABLE edablkfl_sql
DROP TABLE edacumfl_sql
DROP TABLE edapkgfl_sql
DROP TABLE edatmp03_sql
DROP TABLE edatpqfl_sql
DROP TABLE edatpsfl_sql
DROP TABLE edbbcifl_sql
DROP TABLE edcaudfl_sql
DROP TABLE edccapfl_sql
DROP TABLE edcchgfl_sql
DROP TABLE edcctlfl_sql
DROP TABLE edcitmfl_sql
DROP TABLE edclogfl_sql
DROP TABLE edcsdqfl_sql
DROP TABLE edcshtfl_sql
DROP TABLE edcshvfl_sql
DROP TABLE edctmp02_sql
DROP TABLE edctp_fl_sql
DROP TABLE edi_adfl_sql
DROP TABLE edi_csfl_sql
DROP TABLE edi_ddfl_sql
DROP TABLE edi_edfl_sql
DROP TABLE edi_epfl_sql
DROP TABLE edi_eufl_sql
DROP TABLE edi_sdfl_sql
DROP TABLE edi_ssfl_sql
DROP TABLE edi_sufl_sql
DROP TABLE edi_tdfl_sql
DROP TABLE edi_tsfl_sql
DROP TABLE edi_vdfl_sql
DROP TABLE edscrfil_sql
|
REPLACE INTO `sys_role` (`id`, `name`, `handle`) VALUES
(1, 'Everyone', 'everyone'),
(2, 'Administrators', 'admins');
|
CREATE TABLE [display].[core_country]
(
[active_display_value] NVARCHAR(80) NULL,
[iana_display_value] NVARCHAR(80) NULL,
[iso3166_2_display_value] NVARCHAR(80) NULL,
[iso3166_3_display_value] NVARCHAR(80) NULL,
[name_display_value] NVARCHAR(255) NULL,
[order_display_value] NVARCHAR(80) NULL,
[population_display_value] NVARCHAR(80) NULL,
[sys_created_by_display_value] NVARCHAR(80) NULL,
[sys_created_on_display_value] NVARCHAR(80) NULL,
[sys_id_display_value] NVARCHAR(255) NULL,
[sys_mod_count_display_value] NVARCHAR(80) NULL,
[sys_tags_display_value] NVARCHAR(80) NULL,
[sys_updated_by_display_value] NVARCHAR(80) NULL,
[sys_updated_on_display_value] NVARCHAR(80) NULL,
[un_numeric_display_value] NVARCHAR(80) NULL,
)
|
select
count(id) as count
from
gha_events
where
created_at >= '{{from}}'
and created_at < '{{to}}'
;
|
create index IX_58F76CCF on Newsletter_NewsletterCampaign (contentId);
create index IX_7E53C70B on Newsletter_NewsletterCampaign (sendDate, sent);
create index IX_A93605DF on Newsletter_NewsletterCampaign (uuid_);
create unique index IX_313E99AB on Newsletter_NewsletterCampaign (uuid_, groupId);
create index IX_C17426C5 on Newsletter_NewsletterContact (email);
create index IX_A28728F4 on Newsletter_NewsletterContent (uuid_);
create unique index IX_378B1E36 on Newsletter_NewsletterContent (uuid_, groupId);
create index IX_4DCAD2CA on Newsletter_NewsletterLog (campaignId);
create index IX_DA01CD41 on Newsletter_NewsletterLog (campaignId, contactId);
create index IX_55EBA8D6 on Newsletter_NewsletterLog (campaignId, sent);
create index IX_E3901C20 on Newsletter_NewsletterLog (contactId); |
-- phpMyAdmin SQL Dump
-- version 3.2.3
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jul 15, 2011 at 01:29 AM
-- Server version: 5.1.42
-- PHP Version: 5.3.4
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
--
-- Database: `WhatWeWanna`
--
-- --------------------------------------------------------
--
-- Table structure for table `notes`
--
CREATE TABLE IF NOT EXISTS `notes` (
id INT AUTO_INCREMENT PRIMARY KEY ,
name TEXT NOT NULL ,
description TEXT NOT NULL,
address TEXT NOT NULL,
latitude TEXT NOT NULL,
longitude TEXT NOT NULL,
tags TEXT
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
id INT AUTO_INCREMENT PRIMARY KEY ,
name TEXT NOT NULL ,
email TEXT NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
|
CREATE TABLE todays_price
(
date DATE NOT NULL,
company_name VARCHAR(255) NOT NULL,
amount NUMERIC(19, 2) NOT NULL,
closing_price NUMERIC(19, 2) NOT NULL,
difference NUMERIC(19, 2) NOT NULL,
max_price NUMERIC(19, 2) NOT NULL,
min_price NUMERIC(19, 2) NOT NULL,
no_of_transactions INTEGER NOT NULL,
previous_closing NUMERIC(19, 2) NOT NULL,
traded_shares INTEGER NOT NULL,
value_date DATE NOT NULL,
value_time TIME NOT NULL,
CONSTRAINT todays_price_pkey
PRIMARY KEY (date, company_name)
); |
create table temp2 as
select
h.provider_id,
h.hospital_ownership,
ec.measure_name,
ec.score
from hospitals h join effective_care ec ON (h.provider_id = ec.provider_id)
where ec.score not like 'Not';
|
# 1. 테이블 생성
CREATE TABLE `booking` (
`id` int NOT NULL AUTO_INCREMENT primary key,
`name` varchar(32) NOT NULL,
`headcount` int NOT NULL,
`day`int NOT NULL,
`date` timestamp NOT NULL,
`phoneNumber`varchar(16),
`state`varchar(4),
`createdAt` timestamp DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
# 2. 데이터 저장
INSERT INTO `booking` (`name`, `headcount`, `day`, `date`, `phoneNumber`, `state`, `createdAt`, `updatedAt`)
VALUES ('강하늘', 2, 1, '2025-07-21', '010-1234-1111', '대기중', now(), now()),
('김종국', 4, 1, '2025-08-04', '010-1212-2121', '확정', now(), now()),
('박명수', 2, 4, '2025-06-12', '010-0000-0000', '취소', now(), now()),
('마동석', 2, 1, '2025-10-30 ', '010-1010-0101', '대기중', now(), now()),
('박나래', 10, 3, '2025-06-23', '010-1111-2222', '확정', now(), now()),
('혜리', 2, 2, '2025-04-12', '010-9999-9999', '확정', now(), now()),
('황찬성', 25, 1, '2025-09-11', '010-0000-2222', '확정', now(), now()),
('탁재훈', 4, 3, '2025-07-12', '010-1111-0000', '대기중', now(), now()),
('장나라', 2, 1, '2025-09-12', '010-2222-0000', '확정', now(), now());
# 3. 날짜 조건
SELECT `name`, `day`, `date`FROM `booking`WHERE date > '2025-08-01 00:00:00';
# 4. 복합 조건
SELECT `name`, `headcount`, `day`, `state` FROM `booking`
WHERE `state`= '확정' AND (`headcount` >= 4 OR `day` >= 2);
# 5. 카운트
SELECT count(*) FROM `booking` WHERE `day` = 1 AND `state`= '대기중';
# 6. 예약 상태 변경
UPDATE `booking` SET `state`= '취소' WHERE `name` = '마동석' OR `name`= '탁재훈';
# 7. 취소 삭제
SELECT * FROM `booking` WHERE `state` = '취소';
DELETE FROM `booking`WHERE `state`= '취소'; |
CREATE TABLE TestPerson (
id INT NOT NULL PRIMARY KEY IDENTITY(1,1),
FirstName NVARCHAR(100) NOT NULL,
LastName NVARCHAR(100) NOT NULL,
EmailAddress NVARCHAR(200) NOT NULL,
PhoneNumber VARCHAR(20),
NumberOfKids INT NOT NULL,
CreateDate DATETIME2(7) NOT NULL,
);
ALTER TABLE TestPerson
ADD CONSTRAINT NOKCD_DEFAULT
DEFAULT GETDATE() FOR CreateDate,
DEFAULT 0 FOR NumberOfKidS;
DROP TABLE TestPerson
INSERT INTO TestPerson (FirstName,LastName,EmailAddress,PhoneNumber,NumberOfKids)
VALUES ('Tim','Corey','test@corey.com','555-121212',2)
INSERT INTO TestPerson (FirstName,LastName,EmailAddress,PhoneNumber)
VALUES ('Jim','Smith','hello@world.com','555-1212')
CREATE PROC spPrizes_GetByTournament
@TournamentId Int
AS
BEGIN
SET NOCOUNT ON
SELECT p. *
FROM dbo.Prizes p
INNER JOIN dbo.TournamentPrizes t on p.id = t.PrizeId
WHERE t.TournamentId = @TournamentId;
END
CREATE PROC spTestPerson_GetByLastName
@LastName nvarchar(100)
AS
BEGIN
SET NOCOUNT ON
SELECT * FROM TestPerson WHERE LastName = @LastName;
END
exec spTestPerson_GetByLastName @LastName = 'Smith'
SELECT * FROM TestPerson |
/*
Navicat Premium Data Transfer
Source Server : localhost_3306
Source Server Type : MySQL
Source Server Version : 80012
Source Host : 127.0.0.1:3306
Source Schema : crud_db
Target Server Type : MySQL
Target Server Version : 80012
File Encoding : 65001
Date: 18/11/2019 20:20:07
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for product
-- ----------------------------
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`product_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`product_price` decimal(10, 0) NULL DEFAULT NULL,
`createdAt` timestamp(0) NULL DEFAULT NULL,
`updatedAt` timestamp(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0),
PRIMARY KEY (`product_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of product
-- ----------------------------
INSERT INTO `product` VALUES (10, 'lb8hk', 2000, '2019-11-18 20:18:34', '2019-11-18 20:19:41');
INSERT INTO `product` VALUES (11, '33333', 444, '2019-11-18 20:18:44', '2019-11-18 20:18:44');
INSERT INTO `product` VALUES (12, 'สินค้า 1', 30000, '2019-11-18 20:18:56', '2019-11-18 20:18:56');
SET FOREIGN_KEY_CHECKS = 1;
|
-- MySQL dump 10.16 Distrib 10.1.33-MariaDB, for Linux (x86_64)
--
-- Host: localhost Database: sbi
-- ------------------------------------------------------
-- Server version 10.1.33-MariaDB
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `address`
--
DROP TABLE IF EXISTS `address`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `address` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`cep` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`complement` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`district` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`number` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`street` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`city_id` bigint(20) DEFAULT NULL,
`client_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FKpo044ng5x4gynb291cv24vtea` (`city_id`),
KEY `FK7156ty2o5atyuy9f6kuup9dna` (`client_id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `address`
--
LOCK TABLES `address` WRITE;
/*!40000 ALTER TABLE `address` DISABLE KEYS */;
INSERT INTO `address` VALUES (1,'40000000',NULL,'Pituba','0','Rua dos Bobos',1,1),(2,'74847153',NULL,'Avenida Zorro','666','Rua Paulista',3,2);
/*!40000 ALTER TABLE `address` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `category`
--
DROP TABLE IF EXISTS `category`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `category` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `category`
--
LOCK TABLES `category` WRITE;
/*!40000 ALTER TABLE `category` DISABLE KEYS */;
INSERT INTO `category` VALUES (1,'Informatica'),(2,'Escritorio'),(3,'Cama mesa e banho'),(4,'Eletrônicos'),(5,'Jardinagem'),(6,'Decoração'),(7,'Perfumaria');
/*!40000 ALTER TABLE `category` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `city`
--
DROP TABLE IF EXISTS `city`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `city` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`province_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FKll21eddgtrjc9f40ueeouyr8f` (`province_id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `city`
--
LOCK TABLES `city` WRITE;
/*!40000 ALTER TABLE `city` DISABLE KEYS */;
INSERT INTO `city` VALUES (1,'Salvador',1),(2,'Simões Filho',1),(3,'São Paulo',2);
/*!40000 ALTER TABLE `city` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `client`
--
DROP TABLE IF EXISTS `client`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `client` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`client_type` int(11) DEFAULT NULL,
`cpf_cnpj` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`address_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FKb137u2cl2ec0otae32lk5pcl2` (`address_id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `client`
--
LOCK TABLES `client` WRITE;
/*!40000 ALTER TABLE `client` DISABLE KEYS */;
INSERT INTO `client` VALUES (1,0,'87782461480',NULL,'Maria Silva',1),(2,1,'51418224278',NULL,'João Silva',2);
/*!40000 ALTER TABLE `client` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `client_requests`
--
DROP TABLE IF EXISTS `client_requests`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `client_requests` (
`client_id` bigint(20) NOT NULL,
`requests_id` bigint(20) NOT NULL,
UNIQUE KEY `UK_nbmbc4bouaw8ofhvatgwcp8k4` (`requests_id`),
KEY `FKsojqx4mw0vkgkih79y8shqwnh` (`client_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `client_requests`
--
LOCK TABLES `client_requests` WRITE;
/*!40000 ALTER TABLE `client_requests` DISABLE KEYS */;
INSERT INTO `client_requests` VALUES (1,1),(1,2);
/*!40000 ALTER TABLE `client_requests` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `client_telephones`
--
DROP TABLE IF EXISTS `client_telephones`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `client_telephones` (
`client_id` bigint(20) NOT NULL,
`telephones_id` bigint(20) NOT NULL,
UNIQUE KEY `UK_f74uw9b42qbsqc1r8b07wcdwo` (`telephones_id`),
KEY `FKdlo52on1hqquv3bqg7lyuqxhk` (`client_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `client_telephones`
--
LOCK TABLES `client_telephones` WRITE;
/*!40000 ALTER TABLE `client_telephones` DISABLE KEYS */;
INSERT INTO `client_telephones` VALUES (1,1),(2,2);
/*!40000 ALTER TABLE `client_telephones` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `payment`
--
DROP TABLE IF EXISTS `payment`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payment` (
`request_id` bigint(20) NOT NULL,
`payment_status` int(11) DEFAULT NULL,
PRIMARY KEY (`request_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `payment`
--
LOCK TABLES `payment` WRITE;
/*!40000 ALTER TABLE `payment` DISABLE KEYS */;
INSERT INTO `payment` VALUES (1,1),(2,0);
/*!40000 ALTER TABLE `payment` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `payment_card`
--
DROP TABLE IF EXISTS `payment_card`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payment_card` (
`number_parcels` int(11) DEFAULT NULL,
`request_id` bigint(20) NOT NULL,
PRIMARY KEY (`request_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `payment_card`
--
LOCK TABLES `payment_card` WRITE;
/*!40000 ALTER TABLE `payment_card` DISABLE KEYS */;
INSERT INTO `payment_card` VALUES (5,1);
/*!40000 ALTER TABLE `payment_card` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `payment_ticket`
--
DROP TABLE IF EXISTS `payment_ticket`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payment_ticket` (
`payment_date` datetime DEFAULT NULL,
`sale_date` datetime DEFAULT NULL,
`request_id` bigint(20) NOT NULL,
PRIMARY KEY (`request_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `payment_ticket`
--
LOCK TABLES `payment_ticket` WRITE;
/*!40000 ALTER TABLE `payment_ticket` DISABLE KEYS */;
INSERT INTO `payment_ticket` VALUES ('2017-11-30 03:25:00',NULL,2);
/*!40000 ALTER TABLE `payment_ticket` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `product`
--
DROP TABLE IF EXISTS `product`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `product` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`price` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `product`
--
LOCK TABLES `product` WRITE;
/*!40000 ALTER TABLE `product` DISABLE KEYS */;
INSERT INTO `product` VALUES (1,'Computador',2000),(2,'Impressora',800),(3,'Mouse',80),(4,'Mesa de escritório',300),(5,'Toalha',50),(6,'Colcha',200),(7,'TV true color',1200),(8,'Roçadeira',800),(9,'Abajour',100),(10,'Pendente',180),(11,'Shampoo',90);
/*!40000 ALTER TABLE `product` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `product_category`
--
DROP TABLE IF EXISTS `product_category`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `product_category` (
`product_id` bigint(20) NOT NULL,
`category_id` bigint(20) NOT NULL,
KEY `FKkud35ls1d40wpjb5htpp14q4e` (`category_id`),
KEY `FK2k3smhbruedlcrvu6clued06x` (`product_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `product_category`
--
LOCK TABLES `product_category` WRITE;
/*!40000 ALTER TABLE `product_category` DISABLE KEYS */;
INSERT INTO `product_category` VALUES (1,1),(1,1),(1,4),(2,1),(2,2),(2,1),(2,2),(2,4),(3,1),(3,1),(3,4),(4,2),(5,3),(6,3),(7,4),(8,5),(9,6),(10,6),(11,7);
/*!40000 ALTER TABLE `product_category` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `province`
--
DROP TABLE IF EXISTS `province`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `province` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`uf` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `province`
--
LOCK TABLES `province` WRITE;
/*!40000 ALTER TABLE `province` DISABLE KEYS */;
INSERT INTO `province` VALUES (1,'Bahia','BA'),(2,'São Paulo','SP');
/*!40000 ALTER TABLE `province` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `request`
--
DROP TABLE IF EXISTS `request`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `request` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`instant` datetime DEFAULT NULL,
`address_id` bigint(20) DEFAULT NULL,
`client_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK5lgq31tbbs7hag7npu31ha3l4` (`address_id`),
KEY `FKdayt1j0e3kc0j52bn9b78dav` (`client_id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `request`
--
LOCK TABLES `request` WRITE;
/*!40000 ALTER TABLE `request` DISABLE KEYS */;
INSERT INTO `request` VALUES (1,'2017-09-30 17:41:00',1,1),(2,'2017-09-30 09:28:00',2,2);
/*!40000 ALTER TABLE `request` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `request_item`
--
DROP TABLE IF EXISTS `request_item`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `request_item` (
`amount` int(11) DEFAULT NULL,
`discount` double DEFAULT NULL,
`price` double DEFAULT NULL,
`product_id` bigint(20) NOT NULL,
`request_id` bigint(20) NOT NULL,
PRIMARY KEY (`product_id`,`request_id`),
KEY `FKd2t6dw5gx34u1me7451b64xq3` (`request_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `request_item`
--
LOCK TABLES `request_item` WRITE;
/*!40000 ALTER TABLE `request_item` DISABLE KEYS */;
INSERT INTO `request_item` VALUES (1,0,2000,1,1),(2,0,200,3,1),(1,100,800,2,2);
/*!40000 ALTER TABLE `request_item` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `telephone`
--
DROP TABLE IF EXISTS `telephone`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `telephone` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`code_province` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`telephone` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `telephone`
--
LOCK TABLES `telephone` WRITE;
/*!40000 ALTER TABLE `telephone` DISABLE KEYS */;
INSERT INTO `telephone` VALUES (1,'71','991487946'),(2,'71','30478489');
/*!40000 ALTER TABLE `telephone` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2018-06-21 8:41:56
|
create or replace view v_gwysfzxx as
select b.de042 as de042,b.c10,a.scolxbval,b.c31 as scolsfzval,a.scolqsrqval from shzjcb a,gz011cz b where a.c9 = b.c9 and
b.de011 = 2013 and b.de007 = '07' and b.jsdeg124 =1 and b.czde701 = 1
and b.czde103 in (20130000000122,20130000000124,20130000000126) order by de042,c10
|
CREATE TABLE PLAYER_ABILITIES (
ID INT NOT NULL,
PLAYER_ID INT,
SKILL_ID INT,
ABILITY_VALUE DECIMAL(5,2) NOT NULL,
CONSTRAINT PLAYER_ABILITIES_PK PRIMARY KEY (ID),
CONSTRAINT PLAYER_ABILIT_PLAYER_FK FOREIGN KEY (PLAYER_ID) REFERENCES PLAYERS(ID),
CONSTRAINT PLAYER_ABILIT_SKILL_FK FOREIGN KEY (SKILL_ID) REFERENCES SKILLS(ID)
); |
/*
Name: Listings saved by Language
Data source: 4
Created By: Admin
Last Update At: 2016-03-02T18:46:07.154889+00:00
*/
select post_prop64,count(*)
from(
SELECT string(post_prop26) Listing, post_prop64
FROM (TABLE_QUERY(djomniture:cipomniture_djmansionglobal,'CONCAT(REPLACE(table_id,"_","-"),"-01") BETWEEN STRFTIME_UTC_USEC("{{startdate}}", "%Y-%m-01") and STRFTIME_UTC_USEC("{{enddate}}", "%Y-%m-31")'))
WHERE post_page_event='100'
AND DATE(date_time) >= DATE('{{startdate}}')
AND DATE(date_time) <= DATE('{{enddate}}')
AND (post_prop25 = "listingSaved")
GROUP BY Listing,post_prop64)
group by post_prop64
|
-- ash-current-waits-by-sql.sql
-- find the current top 20 SQL by execution time per session that occurred in a single session
-- Jared Still - jkstill@gmail.com
set pause off echo off
set feed on term on
set pagesize 200
set linesize 200 trimspool on
col wait_class format a20 head 'WAIT CLASS'
col sql_id format a13 head 'SQL ID'
col session_serial# format 99999999 head 'SESSION|SERIAL#'
col sql_time format 999,999,999 head 'SQL TIME(s)'
with sqldata as (
select distinct
sql_id
,session_id
, session_serial#
, sql_exec_id
, count(*) over (partition by sql_id, session_id, session_serial#, sql_exec_id) sql_time
from v$active_session_history h
where time_waited != 0
and sql_id is not null
order by 5 desc
)
select sql_id
, sql_time
from sqldata
where rownum <= 20
order by sql_time
/
|
DROP TABLE IF EXISTS `emailsenders`;
CREATE TABLE `emailsenders` (
`id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`email` VARCHAR(255),
`name` VARCHAR(255),
`username` VARCHAR(255),
`password` VARCHAR(255),
`createdat` DATETIME,
`updatedat` DATETIME,
`deletedat` DATETIME
);
INSERT INTO `emailsenders` ( `name`,`email`,`username`,`password` ) VALUES ( 'BMAI','BMAI@bmai.org','BMAI@bmai.org','BM@!' );
|
create table DirectMarketing(
DirectMarketingId int,
DirectMarketingInFo varchar(50),
DirectMarketingType varchar(50));
ALTER TABLE DirectMarketing add CompanyName varchar(50);
ALTER TABLE DirectMarketing add ClientId int NOT NULL;
ALTER TABLE DirectMarketing
ADD CONSTRAINT PK_DirectMarketing PRIMARY KEY (DirectMarketingId );
ALTER TABLE DirectMarketing
ADD CONSTRAINT FK_DirectMarketing FOREIGN KEY (ClientId) REFERENCES Clients(ClientId);
ALTER TABLE DirectMarketing
ADD CONSTRAINT df_DirectMarketingType
DEFAULT 'Direct Selling' FOR DirectMarketingType;
|
--카드삭제
delete from card where card_no=1;
--유저가 가지고 있는 카드리스트
select * from card join userinfo on card.user_no = userinfo.user_no where card.user_no=1;
--카드번호에 따른 존재여부 확인
select count(*) isexisted from card where card_realno='1111-1111-1111-1111';
--카드번호
select substr(card_realno, 1, 4) || '-****-****-' ||
substr(card_realno, 16, 4) as card_realno from card where card_no=2; |
-- phpMyAdmin SQL Dump
-- version 4.6.6
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Mar 29, 2017 at 07:03 AM
-- Server version: 5.7.17
-- PHP Version: 7.1.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `cestore`
--
-- --------------------------------------------------------
--
-- Table structure for table `addresses`
--
CREATE TABLE `addresses` (
`id` int(11) NOT NULL,
`address_1` varchar(255) NOT NULL,
`address_2` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`state` varchar(255) NOT NULL,
`country_id` int(11) NOT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `addresses_customers`
--
CREATE TABLE `addresses_customers` (
`id` int(11) NOT NULL,
`address_id` int(11) NOT NULL,
`customer_id` int(11) NOT NULL,
`is_billing_default` tinyint(1) NOT NULL,
`is_shipping_default` tinyint(1) NOT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `categories`
--
CREATE TABLE `categories` (
`id` int(11) NOT NULL,
`department_id` int(11) NOT NULL,
`code` varchar(10) NOT NULL,
`name` varchar(255) NOT NULL,
`description` varchar(4000) DEFAULT NULL,
`picture_file_name` varchar(255) DEFAULT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `customers`
--
CREATE TABLE `customers` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`first_name` varchar(50) NOT NULL,
`last_name` varchar(50) NOT NULL,
`company_name` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `departments`
--
CREATE TABLE `departments` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`description` varchar(4000) NOT NULL,
`picture_file_name` varchar(255) DEFAULT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `items`
--
CREATE TABLE `items` (
`id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`manufacturer_id` int(11) NOT NULL,
`code` varchar(20) NOT NULL,
`short_name` varchar(50) DEFAULT NULL,
`name` varchar(255) NOT NULL,
`description` varchar(4000) NOT NULL,
`picture_group_id` int(11) DEFAULT NULL,
`measurement_unit` varchar(50) DEFAULT NULL,
`color` varchar(255) DEFAULT NULL,
`size` varchar(255) DEFAULT NULL,
`weight` int(11) DEFAULT NULL,
`quantity_on_hand` int(11) NOT NULL,
`is_discontinued` tinyint(1) DEFAULT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `line_items`
--
CREATE TABLE `line_items` (
`id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`order_id` int(11) NOT NULL,
`quantity` int(11) NOT NULL,
`price` int(11) NOT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `manufacturers`
--
CREATE TABLE `manufacturers` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`phone` varchar(50) NOT NULL,
`homepage` varchar(255) NOT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `orders`
--
CREATE TABLE `orders` (
`id` int(11) NOT NULL,
`customer_id` int(11) NOT NULL,
`address_customer_id` int(11) NOT NULL,
`description` varchar(4000) NOT NULL,
`order_date` date NOT NULL,
`sub_total` int(11) NOT NULL,
`discount` int(11) NOT NULL,
`total` bigint(20) NOT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `password_resets`
--
CREATE TABLE `password_resets` (
`id` int(11) NOT NULL,
`email` varchar(255) NOT NULL,
`token` varchar(255) DEFAULT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `prices`
--
CREATE TABLE `prices` (
`id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`value` int(11) NOT NULL,
`set_date` datetime NOT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `procurements`
--
CREATE TABLE `procurements` (
`id` int(11) NOT NULL,
`supplier_id` int(11) NOT NULL,
`description` int(11) NOT NULL,
`procurement_date` datetime NOT NULL,
`order_number` int(11) NOT NULL,
`total` int(11) NOT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `procurement_details`
--
CREATE TABLE `procurement_details` (
`id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`procurement_id` int(11) NOT NULL,
`quantity` int(11) NOT NULL,
`price` int(11) NOT NULL,
`sub_total` int(11) NOT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `suppliers`
--
CREATE TABLE `suppliers` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`contact_name` varchar(50) NOT NULL,
`contact_title` varchar(50) NOT NULL,
`address` varchar(255) NOT NULL,
`phone` varchar(50) NOT NULL,
`fax` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`homepage` varchar(255) NOT NULL,
`is_direct_sales` tinyint(1) NOT NULL DEFAULT '0',
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`remember_token` varchar(100) DEFAULT NULL,
`encrypted_password` varchar(128) DEFAULT NULL,
`is_employee` tinyint(1) NOT NULL DEFAULT '0',
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `addresses`
--
ALTER TABLE `addresses`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `addresses_customers`
--
ALTER TABLE `addresses_customers`
ADD PRIMARY KEY (`id`),
ADD KEY `id_idx1` (`customer_id`),
ADD KEY `address_id_idx` (`address_id`);
--
-- Indexes for table `categories`
--
ALTER TABLE `categories`
ADD PRIMARY KEY (`id`),
ADD KEY `departmnet_id_idx` (`department_id`);
--
-- Indexes for table `customers`
--
ALTER TABLE `customers`
ADD PRIMARY KEY (`id`),
ADD KEY `user_id` (`user_id`);
--
-- Indexes for table `departments`
--
ALTER TABLE `departments`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `items`
--
ALTER TABLE `items`
ADD PRIMARY KEY (`id`),
ADD KEY `category_id_idx` (`category_id`),
ADD KEY `manufacturer_id` (`manufacturer_id`);
--
-- Indexes for table `line_items`
--
ALTER TABLE `line_items`
ADD PRIMARY KEY (`id`),
ADD KEY `item_id` (`item_id`),
ADD KEY `order_id` (`order_id`);
--
-- Indexes for table `manufacturers`
--
ALTER TABLE `manufacturers`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `orders`
--
ALTER TABLE `orders`
ADD PRIMARY KEY (`id`),
ADD KEY `customer_id2` (`customer_id`),
ADD KEY `address_customer_id` (`address_customer_id`);
--
-- Indexes for table `password_resets`
--
ALTER TABLE `password_resets`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `prices`
--
ALTER TABLE `prices`
ADD PRIMARY KEY (`id`),
ADD KEY `item_id2` (`item_id`);
--
-- Indexes for table `procurements`
--
ALTER TABLE `procurements`
ADD PRIMARY KEY (`id`),
ADD KEY `supplier_id` (`supplier_id`);
--
-- Indexes for table `procurement_details`
--
ALTER TABLE `procurement_details`
ADD PRIMARY KEY (`id`),
ADD KEY `item_id3` (`item_id`),
ADD KEY `procurement_id` (`procurement_id`);
--
-- Indexes for table `suppliers`
--
ALTER TABLE `suppliers`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `addresses`
--
ALTER TABLE `addresses`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `addresses_customers`
--
ALTER TABLE `addresses_customers`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `categories`
--
ALTER TABLE `categories`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `customers`
--
ALTER TABLE `customers`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `departments`
--
ALTER TABLE `departments`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `items`
--
ALTER TABLE `items`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `line_items`
--
ALTER TABLE `line_items`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `manufacturers`
--
ALTER TABLE `manufacturers`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `orders`
--
ALTER TABLE `orders`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `password_resets`
--
ALTER TABLE `password_resets`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `prices`
--
ALTER TABLE `prices`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `procurements`
--
ALTER TABLE `procurements`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `procurement_details`
--
ALTER TABLE `procurement_details`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `suppliers`
--
ALTER TABLE `suppliers`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `addresses_customers`
--
ALTER TABLE `addresses_customers`
ADD CONSTRAINT `address_id` FOREIGN KEY (`address_id`) REFERENCES `addresses` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `customer_id` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `categories`
--
ALTER TABLE `categories`
ADD CONSTRAINT `departmnet_id` FOREIGN KEY (`department_id`) REFERENCES `departments` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `customers`
--
ALTER TABLE `customers`
ADD CONSTRAINT `user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `items`
--
ALTER TABLE `items`
ADD CONSTRAINT `category_id` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `manufacturer_id` FOREIGN KEY (`manufacturer_id`) REFERENCES `manufacturers` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `line_items`
--
ALTER TABLE `line_items`
ADD CONSTRAINT `item_id` FOREIGN KEY (`item_id`) REFERENCES `items` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `order_id` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `orders`
--
ALTER TABLE `orders`
ADD CONSTRAINT `address_customer_id` FOREIGN KEY (`address_customer_id`) REFERENCES `addresses_customers` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `customer_id2` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `prices`
--
ALTER TABLE `prices`
ADD CONSTRAINT `item_id2` FOREIGN KEY (`item_id`) REFERENCES `items` (`id`);
--
-- Constraints for table `procurements`
--
ALTER TABLE `procurements`
ADD CONSTRAINT `supplier_id` FOREIGN KEY (`supplier_id`) REFERENCES `suppliers` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `procurement_details`
--
ALTER TABLE `procurement_details`
ADD CONSTRAINT `item_id3` FOREIGN KEY (`item_id`) REFERENCES `items` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `procurement_id` FOREIGN KEY (`procurement_id`) REFERENCES `procurements` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
create user YKT_CUR
identified by "kingstar"
default tablespace TS_YKT_CUR
temporary tablespace TEMP
profile DEFAULT
quota unlimited on ts_ykt_cur
quota unlimited on ts_ykt_his;
-- Grant/Revoke role privileges
grant connect to YKT_CUR with admin option;
grant dba to YKT_CUR;
grant resource to YKT_CUR with admin option;
-- Grant/Revoke system privileges
grant create any synonym to YKT_CUR with admin option;
grant create procedure to YKT_CUR with admin option;
grant create trigger to YKT_CUR with admin option;
grant create public synonym to YKT_CUR with admin option;
grant create table to YKT_CUR with admin option;
grant create view to YKT_CUR with admin option;
grant drop any procedure to YKT_CUR with admin option;
grant drop any synonym to YKT_CUR with admin option;
grant drop any table to YKT_CUR with admin option;
grant drop any view to YKT_CUR with admin option;
grant drop public synonym to YKT_CUR with admin option;
grant select any dictionary to YKT_CUR with admin option;
grant unlimited tablespace to YKT_CUR with admin option;
create user YKT_PORTAL
identified by "ykt4portal"
default tablespace TS_YKT_WEB
temporary tablespace TEMP
profile DEFAULT
quota unlimited on TS_YKT_WEB;
grant create any index to YKT_PORTAL;
grant create any table to YKT_PORTAL;
grant create any view to YKT_PORTAL;
grant create any procedure to YKT_PORTAL;
grant create any trigger to YKT_PORTAL;
grant drop any table to YKT_PORTAL;
grant drop any procedure to YKT_PORTAL;
grant drop any trigger to YKT_PORTAL;
grant drop any view to YKT_PORTAL;
GRANT CONNECT TO YKT_PORTAL;
create user YKT_CK
identified by "kingstar"
default tablespace TS_YKT_CUR
temporary tablespace TEMP
profile DEFAULT
quota unlimited on TS_YKT_CUR;
GRANT CONNECT TO YKT_CK; |
SELECT
job_id,
department_id
FROM
employees;
-- 중복 제거: distinct
SELECT DISTINCT
job_id,
department_id
FROM
employees;
SELECT
job_id,
department_id
FROM
employees;
--문자 타입 함수
SELECT
last_name,
lower(last_name) AS lower적용,
upper(last_name) AS upper적용,
email,
initcap(email) initcap적용
FROM
employees;
-- job_id의 첫째 자리에서 시작해서 2개의 문자 출력 : SUBSTR()
SELECT
job_id,
substr(job_id, 1, 2) 직무코드
FROM
employees;
-- job_id 문자열 값이 'ACCOUNT'이면 'ACCNT'로 출력 : REPLACE()
SELECT
job_id,
replace(job_id, 'ACCOUNT', 'ACCNT') 결과
FROM
employees;
--12자리의 문자열의 자리를 부족한 만큼 '*' 로 채워서 출력
SELECT
first_name,
lpad(first_name, 12, '*') 결과
FROM
employees;
SELECT
first_name,
rpad(first_name, 24 / 2, '*') 결과
FROM
employees;
-- 숫자 타입 함수
SELECT
salary,
salary / 30 일급,
round(salary / 30, 1) 결과1, --소수첫째자리까지 반올림 출력
round(salary / 30, 0) 결과2, --정수형
round(salary / 30, - 1) 결과3 --일의 자리에서 반올림
FROM
employees;
-- TRUNC() -> 버림(절삭)
SELECT
salary,
salary / 30 일급,
trunc(salary / 30, 1) 결과1, --소수첫째자리까지 내림 출력
trunc(salary / 30, 0) 결과2, --정수형
trunc(salary / 30, - 1) 결과3 --일의 자리에서 내림
FROM
employees;
-- 날짜 타입 함수
-- department_id가 100인 직원에 대해 입사후 총 개월수 출력
SELECT
first_name,
department_id,
sysdate,
hire_date,
trunc(months_between(sysdate, hire_date)) 총_개월수
FROM
employees;
--employee_id 가 100에서 106번 사이의 직원의 hire_date에 3개월을 더하고 뺀 결과
SELECT
first_name,
employee_id,
hire_date,
add_months(hire_date, 3) 더하기_결과,
add_months(hire_date, - 3) 빼기기_결과
FROM
employees
WHERE
employee_id BETWEEN 100 AND 106;
SELECT
*
FROM
departments; |
CREATE PROCEDURE SP_Save_StockOutDetail
(
@StockOutID Int,
@ProductCode nvarchar(15),
@Quantity Decimal(18,6),
@TotalStock Decimal(18,6)
)
As
BEGIN
INSERT INTO StockOutDetail
( StockOutID,
ProductCode,
Quantity,
TotalStock
)VALUES
(
@StockOutID,
@ProductCode,
@Quantity,
@TotalStock
)
END
|
TIPO A
Nombre: <Pon aquí tu nombre>
************************************************************************
INSTRUCCIONES:
==============
-Salva este fichero con las iniciales de tu nombre y apellidos,
en el directorio "C:\Examen\ ":
Ejemplo: José María Rivera Calvete
JMRC.txt
-Pon tu nombre al ejercicio y lee atentamente todas las preguntas.
-Entra en "SQL Plus" con cualquier usuario.
-Carga el script para el examen desde el fichero "Empresa.sql".
-Donde ponga "SQL>", copiarás las sentencias SQL que has utilizado.
-Donde ponga "RESULTADOS:" copiarás el resultado que SQL*Plus te devuelve.
-RECUERDA: guardar, cada cierto tiempo, el contenido de este fichero. Es lo que voy a evaluar, si lo pierdes, lo siento, en la recuperación tendrás otra oportunidad.
PUNTUACIÓN
==========
- Preguntas 1-14: 0,50 puntos cada una
- Pregunta 15: 3 puntos
************************************************************************
Descripción de las tablas:
==========================
CENTROS
-------
# COD_CE NUMBER(2) Código del Centro
* DIRECTOR_CE NUMBER(6) Director del Centro
NOMB_CE VARCHAR2(30) Nombre del Centro (O)
DIRECC_CE VARCHAR2(50) Dirección del Centro (O)
POBLAC_CE VARCHAR2(15) Población del Centro (O)
DEPARTAMENTOS
-------------
# COD_DE NUMBER(3) Código del Departamento
* DIRECTOR_DE NUMBER(6) Director del Departamento
* DEPTJEFE_DE NUMBER(3) Departamento del que depende
* CENTRO_DE NUMBER(2) Centro trabajo (O)
NOMB_DE VARCHAR2(40) Nombre del Departamento (O)
PRESUP_DE NUMBER(11) Presupuesto del Departamento (O)
TIPODIR_DE CHAR(1) Tipo de Director del Departamento (O)
EMPLEADOS
---------
# COD_EM NUMBER(6) Código del Empleado
* DEPT_EM NUMBER(3) Departamento del Empleado (O)
EXTTEL_EM CHAR(9) Extensión telefónica
FECINC_EM DATE Fecha de incorporación del Empleado (O)
FECNAC_EM DATE Fecha de nacimiento del Empleado (O)
DNI_EM VARCHAR2(9) DNI del Empleado (U)
NOMB_EM VARCHAR2(40) Nombre del Empleado (O)
NUMHIJ_EM NUMBER(2) Número de hijos del Empleado (O)
SALARIO_EM NUMBER(9) Salario Anual del Empleado (O)
HIJOS
-----
#*PADRE_HI NUMBER(6) Código del Empleado
# NUMHIJ_HI NUMBER(2) Número del hijo del Empleado
FECNAC_HI DATE Fecha de nacimiento del Hijo (O)
NOMB_HI VARCHAR2(40) Nombre del Hijo (O)
Nota:
# PRIMARY KEY
* FOREIGN KEY
(O) Obligatorio
(U) Único
************************************************************************
1.- Listar el DNI y el complemento familiar de los empleados con hijos.
NOTA: El complemento familiar será el 5% del salario por cada hijo.
SQL>
SELECT DNI_EM, SALARIO_EM*0.05*NUMHIJ_EM COMPSALARIAL
FROM EMPLEADOS
WHERE NUMHIJ_EM > 0;
RESULTADO:
DNI_EM COMPSALARIAL
--------- ------------
55645991T 310000
56646516D 310000
55980648H 80000
64555339D 260000
76138301V 360000
************************************************************************
2.- Listar el nombre del departamento y su masa salarial, de aquel departamento cuya masa salarial sea la máxima.
NOTA: La masa salarial de un departamento es la suma de los salarios de sus empleados.
SQL>
SELECT NOMB_DE, SUM(SALARIO_EM) MSALARIAL
FROM EMPLEADOS, DEPARTAMENTOS
WHERE COD_DE=DEPT_EM
GROUP BY NOMB_DE
HAVING SUM(SALARIO_EM)= (SELECT MAX(SUM(SALARIO_EM))
FROM EMPLEADOS
GROUP BY DEPT_EM);
RESULTADO:
NOMB_DE MSALARIAL
---------------------------------------- ----------
Produccion Zona Sur 27500000
************************************************************************
3.- Listar el nombre, salario anual, fecha de nacimiento y fecha de ingreso de los empleados que ganan menos de 4 millones de pesetas y que nacieron antes de 1990.
SQL>
SELECT NOMB_EM,SALARIO_EM,FECNAC_EM,FECINC_EM
FROM EMPLEADOS
WHERE SALARIO_EM < 4000000
AND FECNAC_EM < '01/01/1990';
RESULTADO:
NOMB_EM SALARIO_EM FECNAC_EM FECINC_EM
---------------------------------------- ---------- ---------- ----------
Conde Alvarez, Jose Antonio 1300000 09/05/1987 17/05/2016
Fernandez Benito, Javier 3200000 12/02/1979 17/02/2016
Jimenez Campos, Alejandro 1600000 18/01/1988 17/08/2015
Leon Vazquez, Rafael 1300000 06/05/1989 17/08/2016
Matito Lozano, Carmen 3200000 09/01/1989 17/05/2016
17 filas seleccionadas.
************************************************************************
4.- Listar el nº de departamentos que tiene asignado cada centro.
SQL>
SELECT NOMB_CE, COUNT(*)
FROM CENTROS, DEPARTAMENTOS
WHERE COD_CE=CENTRO_DE
GROUP BY NOMB_CE;
RESULTADO:
NOMB_CE COUNT(*)
------------------------------ ----------
Oficinas Zona Sur 2
Direccion General 2
Fabrica Zona Sur 2
************************************************************************
5.- Listar los nombres de los departamentos donde hay al menos un trabajador cuyo salario supone más del 40% del presupuesto del departamento.
SQL>
SELECT DISTINCT NOMB_DE
FROM DEPARTAMENTOS, EMPLEADOS
WHERE COD_DE=DEPT_EM
AND SALARIO_EM > PRESUP_DE*0.4;
RESULTADO:
NOMB_DE
----------------------------------------
Administracion Zona Sur
Jefatura Fabrica Zona Sur
************************************************************************
6.- Insertar un departamento con código 900 y nombre 'Ingenieria de sistemas', cuyo presupuesto será igual al doble de la masa salarial del departamento con mayor masa salarial, dicho departamento será del que dependerá éste. El resto de datos serán los del departamento del que depende.
SQL>
INSERT INTO DEPARTAMENTOS
SELECT 900, DIRECTOR_DE, COD_DE, CENTRO_DE, 'Ingenieria de sistemas', 2*SUM(SALARIO_EM), TIPODIR_DE
FROM EMPLEADOS, DEPARTAMENTOS
WHERE COD_DE=DEPT_EM
GROUP BY NOMB_DE, DIRECTOR_DE, COD_DE, CENTRO_DE, TIPODIR_DE
HAVING SUM(SALARIO_EM)= (SELECT MAX(SUM(SALARIO_EM))
FROM EMPLEADOS
GROUP BY DEPT_EM);
RESULTADO:
900 DIRECTOR_DE COD_DE CENTRO_DE 'INGENIERIADESISTEMAS' 3*SUM(SALARIO_EM) T
---- ----------- ---------- ---------- ---------------------- ----------------- -
900 2 300 10 Ingenieria de sistemas 54000000 P
************************************************************************
7.- Modificar el director del departamento 900 al empleado de más edad.
SQL>
UPDATE DEPARTAMENTOS
SET DIRECTOR_DE = (SELECT COD_EM
FROM EMPLEADOS
WHERE FECNAC_EM = (SELECT MIN(FECNAC_EM)
FROM EMPLEADOS))
WHERE COD_DE=900;
************************************************************************
8.- Cambia al departamento 900 a los empleados que eran menores de edad cuando los contrataron.
SQL>
SELECT * FROM EMPLEADOS
WHERE MONTHS_BETWEEN(FECINC_EM,FECNAC_EM)/12<18;
UPDATE EMPLEADOS
SET DEPT_EM = 900
WHERE MONTHS_BETWEEN(FECINC_EM,FECNAC_EM)/12<18;
************************************************************************
9.- Asígnale el 80% del sueldo de 'Jairo' a los empleados del departamento de 'Alberto'.
SQL>
UPDATE EMPLEADOS
SET SALARIO_EM = 0.8*(SELECT SALARIO_EM
FROM EMPLEADOS
WHERE NOMB_EM LIKE '%Jairo%')
WHERE DEPT_EM = (SELECT DEPT_EM
FROM EMPLEADOS
WHERE NOMB_EM LIKE '%Alberto%');
************************************************************************
10.- Modifica la columna SALARIO_EM de la tabla EMPLEADOS para que tenga dos decimales.
SQL>
ALTER TABLE EMPLEADOS MODIFY SALARIO_EM NUMBER(11,2);
RESULTADO:
************************************************************************
11.- Cambia a EUROS los salarios de los empleados. NOTA: un euro = 166,386 ptas.
SQL>
UPDATE EMPLEADOS
SET SALARIO_EM = SALARIO_EM/166.386;
************************************************************************
12.- Modifica todos los datos del campo NOMB_DE de la tabla DEPARTAMENTOS poniendo su contenido en mayúsculas.
SQL>
UPDATE DEPARTAMENTOS
SET NOMB_DE = UPPER(NOMB_DE);
************************************************************************
13.- Añade una restricción sobre el campo NOMB_DE de la tabla DEPARTAMENTOS para que su contenido siempre sea en mayúsculas.
SQL>
ALTER TABLE DEPARTAMENTOS ADD CONSTRAINT MAY_DE CHECK(NOMB_DE = UPPER(NOMB_DE));
************************************************************************
14.- Crear una vista denominada DIRECTORES que incluya el código, nombre del director, nombre de dpto, salario y población donde trabaja de aquellos empleados que son directores de departamentos. Llamar a las columnas COD, NOM, DEP, PTS, y POB respectivamente.
SQL>
CREATE OR REPLACE VIEW DIRECTORES (COD, NOM, DEP, PTS, POB)
AS
SELECT COD_EM, NOMB_EM, NOMB_DE, SALARIO_EM, POBLAC_CE
FROM EMPLEADOS, DEPARTAMENTOS, CENTROS
WHERE COD_EM = DIRECTOR_DE
AND CENTRO_DE = COD_CE;
************************************************************************
15.- Carga el fichero "Datos107.sql", y a partir de la tabla APROBADOS con la siguiente estructura, y utilizando las sentencias que creas convenientes:
ID NUMBER(3) Identificador del opositor
Nombre VARCHAR2(60) (DNI) Apellidos, Nombre del opositor
Fecha DATE Fecha de nacimiento
Nota NUMBER(6) Nota de la prueba
Obtener la tabla OPOSITORES:
# DNI CHAR(8) DNI del opositor
Apel VARCHAR2(40) Apellidos del opositor
Nombre VARCHAR2(20) Nombre del opositor
Fecha DATE Fecha de nacimiento
Nota NUMBER Nota de la prueba
Ejemplo de datos de la tabla APROBADOS:
ID NOMBRE FECHA NOTA
------- ------------------------------------------------------------ ---------- ---------
85 (44261136) MARTINEZ VARO , PEDRO JOSE 19/03/1974 58833
86 (25102011) RUIZ RUBIO , RAFAEL 21/04/1968 58800
DNI APEL NOMBRE FECHA NOTA
-------- ---------------------------------------- --------------- ---------- ---------
44261136 MARTINEZ VARO PEDRO JOSE 19/03/1974 5,8833
25102011 RUIZ RUBIO RAFAEL 21/04/1968 5,8800
SUGERENCIAS:
-- Opción a) Crea la tabla a partir de una sentencia SELECT utilizando las funciones adecuadas. Después, modifica la estructura de la tabla utilizando sentencias "ALTER TABLE OPOSITORES MODIFY ...".
SQL>
DROP TABLE opositores;
CREATE TABLE opositores(
DNI PRIMARY KEY,
Apel,
Nombre,
Fecha,
Nota
)
AS
SELECT
SUBSTR(nombre,2,8) DNI,
SUBSTR(SUBSTR(SUBSTR(nombre,12),0,INSTR(SUBSTR(nombre,12),',')-2),0,40) Apel,
SUBSTR(SUBSTR(SUBSTR(nombre,12),INSTR(SUBSTR(nombre,12),',')+2),0,20) Nombre,
Fecha,
(Nota/10000) Nota
FROM aprobados;
ALTER TABLE opositores MODIFY apel VARCHAR2(40);
ALTER TABLE opositores MODIFY nombre VARCHAR2(20);
ALTER TABLE opositores MODIFY dni CHAR(8);
-- Opción b) Crea la tabla y, posteriormente, inserta los datos a partir de una sentencia SELECT utilizando las funciones adecuadas.
SQL>
DROP TABLE opositores;
CREATE TABLE opositores(
DNI CHAR(8) PRIMARY KEY,
Apel VARCHAR2(40),
Nombre VARCHAR2(20),
Fecha DATE,
Nota NUMBER
);
INSERT INTO opositores
SELECT
SUBSTR(nombre,2,8) DNI,
SUBSTR(SUBSTR(SUBSTR(nombre,12),0,INSTR(SUBSTR(nombre,12),',')-2),0,40) Apel,
SUBSTR(SUBSTR(SUBSTR(nombre,12),INSTR(SUBSTR(nombre,12),',')+2),0,20) Nombre,
Fecha,
(Nota/10000) Nota
FROM aprobados;
|
-- phpMyAdmin SQL Dump
-- version 5.0.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Dec 07, 2020 at 12:25 AM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.2.34
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `mahakal`
--
-- --------------------------------------------------------
--
-- Table structure for table `entry`
--
CREATE TABLE `entry` (
`firstname` varchar(20) NOT NULL,
`lastname` varchar(20) NOT NULL,
`fathername` varchar(20) NOT NULL,
`email` varchar(20) NOT NULL,
`idproof` varchar(20) NOT NULL,
`gender` varchar(10) NOT NULL,
`address` varchar(20) NOT NULL,
`city` varchar(20) NOT NULL,
`state` varchar(20) NOT NULL,
`country` varchar(20) NOT NULL,
`zip` int(10) NOT NULL,
`mobile` int(10) NOT NULL,
`date` int(10) NOT NULL,
`tsize` varchar(10) NOT NULL,
`payment` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `entry`
--
INSERT INTO `entry` (`firstname`, `lastname`, `fathername`, `email`, `idproof`, `gender`, `address`, `city`, `state`, `country`, `zip`, `mobile`, `date`, `tsize`, `payment`) VALUES
('rahul', 'kumar', 'badal', 'shishirrc2@gmail.com', '123456789', 'male', 'Indore', 'Hyderabad', 'MEN F HOSTEL', 'India', 500046, 2147483647, 2020, '25', '6250'),
('rajkumawat', 'kumar', 'xxxxxxx', 'shishirrc2@gmail.com', '1111111111111111111', 'male', 'Indore', 'Hyderabad', 'MEN F HOSTEL', 'India', 500046, 2147483647, 2020, '3', '750');
-- --------------------------------------------------------
--
-- Table structure for table `payment`
--
CREATE TABLE `payment` (
`name` varchar(20) NOT NULL,
`number` varchar(30) NOT NULL,
`exp_month` varchar(10) NOT NULL,
`exp_year` varchar(10) NOT NULL,
`cvv` varchar(5) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `payment`
--
INSERT INTO `payment` (`name`, `number`, `exp_month`, `exp_year`, `cvv`) VALUES
('sachin', '123456789', '12', '23', '123'),
('vinod', '123456789', '12', '12', '123'),
('vinod', '123456789', '12', '12', '123'),
('vinod', '12212121212', '5', '12', '133'),
('hemant', '234567', '12', '5', '123'),
('hemant', '234567', '12', '5', '123'),
('rajkumawat', '3333333333333', '12', '12', '233'),
('rajkumawat', '654234567', '12', '21', '144');
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
use dbtonyskinal2019063;
-- ===================== CRUD de las Tablas =====================
-- -------------- Tabla Tipo_Plato--------------
-- Agregar
DELIMITER $$
create procedure sp_Agregar_Tipo_Plato(in descripcion varchar(100))
BEGIN
insert into Tipo_plato(DescripcionTipo) values(descripcion);
END $$
DELIMITER ;
-- Listar
DELIMITER $$
create procedure sp_Listar_Tipo_Plato()
BEGIN
Select * from Tipo_Plato;
END $$
DELIMITER ;
-- Actualizar
DELIMITER $$
create procedure sp_Actualizar_Tipo_Plato(in codtp int, descripcion varchar(100))
BEGIN
update Tipo_Plato set DescripcionTipo=descripcion where CodigoTipoPlato=codtp;
END $$
DELIMITER ;
-- Eliminar
DELIMITER $$
create procedure sp_Eliminar_Tipo_Plato(in codtp int)
BEGIN
delete from Tipo_Plato where CodigoTipoPlato=codtp;
END $$
DELIMITER ;
-- Buscar
DELIMITER $$
create procedure sp_Buscar_Tipo_Plato(in codtp int)
BEGIN
Select * from Tipo_Plato where CodigoTipoPlato=codtp;
END $$
DELIMITER ;
-- -------------- Tabla Producto--------------
-- Agregar
DELIMITER $$
create procedure sp_Agregar_Producto(in nombreP varchar(150), cant int)
BEGIN
insert into Producto(nombreProducto,Cantidad) values(nombreP,cant);
END $$
DELIMITER ;
-- Listar
DELIMITER $$
create procedure sp_Listar_Producto()
BEGIN
Select * from Producto;
END $$
DELIMITER ;
-- Actualizar
DELIMITER $$
create procedure sp_Actualizar_Producto(in codP int, nombreP varchar(150), cant int)
BEGIN
update Producto set NombreProducto=nombreP, Cantidad=cant where CodigoProducto=codP;
END $$
DELIMITER ;
-- Eliminar
DELIMITER $$
create procedure sp_Eliminar_Producto(in codP int)
BEGIN
delete from Producto where CodigoProducto=codP;
END $$
DELIMITER ;
-- Buscar
DELIMITER $$
create procedure sp_Buscar_Producto(in codP int)
BEGIN
Select * from Producto where CodigoProducto=codP;
END $$
DELIMITER ;
-- -------------- Tabla TipoEmpleado--------------
-- Agregar
DELIMITER $$
create procedure sp_Agregar_TipoEmpleado(in descripcion varchar(100))
BEGIN
insert into TipoEmpleado(Descripcion) values(descripcion);
END $$
DELIMITER ;
-- Listar
DELIMITER $$
create procedure sp_Listar_TipoEmpleado()
BEGIN
Select * from TipoEmpleado;
END $$
DELIMITER ;
-- Actualizar
DELIMITER $$
create procedure sp_Actualizar_TipoEmpleado(in codte int, descripcion varchar(100))
BEGIN
update TipoEmpleado set Descripcion=descripcion where CodigoTipoEmpleado=codte;
END $$
DELIMITER ;
-- Eliminar
DELIMITER $$
create procedure sp_Eliminar_TipoEmpleado(in codte int)
BEGIN
delete from TipoEmpleado where CodigoTipoEmpleado=codte;
END $$
DELIMITER ;
-- Buscar
DELIMITER $$
create procedure sp_Buscar_TipoEmpleado(in codte int)
BEGIN
Select * from TipoEmpleado where CodigoTipoEmpleado=codte;
END $$
DELIMITER ;
-- -------------- Tabla Empleado--------------
-- Agregar
DELIMITER $$
create procedure sp_Agregar_Empleado(in numE int, apellidoE varchar(150), nombreE varchar(150), direccionE varchar(150), telC varchar(10), grado varchar(50), CodTE int)
BEGIN
insert into Empleado(NumeroEmpleado,ApellidosEmpleado,NombreEmpleado,Direccion,TelefonoContacto,GradoCocinero,CodigoTipoEmpleado)
values(numE,apellidoE,nombreE,direccionE,telC,grado,CodTE);
END $$
DELIMITER ;
-- Listar
DELIMITER $$
create procedure sp_Listar_Empleado()
BEGIN
Select * from Empleado;
END $$
DELIMITER ;
-- Actualizar
DELIMITER $$
create procedure sp_Actualizar_Empleado(in codiE int, numE int, apellidoE varchar(150), nombreE varchar(150), direccionE varchar(150), telC varchar(10), grado varchar(50))
BEGIN
update Empleado set NumeroEmpleado=numE, ApellidosEmpleado=apellidoE, NombreEmpleado=nombreE, Direccion=direccionE, TelefonoContacto=telC,
GradoCocinero=grado where CodigoEmpleado=codiE;
END $$
DELIMITER ;
-- Eliminar
DELIMITER $$
create procedure sp_Eliminar_Empleado(in codiE int)
BEGIN
delete from Empleado where CodigoEmpleado=codiE;
END $$
DELIMITER ;
-- Buscar
DELIMITER $$
create procedure sp_Buscar_Empleado(in codiE int)
BEGIN
Select * from Empleado where CodigoEmpleado=codiE;
END $$
DELIMITER ;
-- -------------- Tabla Empresa--------------
-- Agregar
DELIMITER $$
create procedure sp_Agregar_Empresa(in nombreE varchar(150), direccionE varchar(150), telefonoE varchar(10))
BEGIN
insert into Empresa(NombreEmpresa,Direccion,Telefono) values(nombreE,direccionE,telefonoE);
END $$
DELIMITER ;
-- Listar
DELIMITER $$
create procedure sp_Listar_Empresa()
BEGIN
Select * from Empresa;
END $$
DELIMITER ;
-- Actualizar
DELIMITER $$
create procedure sp_Actualizar_Empresa(in codigoE int, nombreE varchar(150), direccionE varchar(150), telefonoE varchar(10))
BEGIN
update Empresa set NombreEmpresa=nombreE, Direccion=direccionE, Telefono=telefonoE where CodigoEmpresa=codigoE;
END $$
DELIMITER ;
-- Eliminar
DELIMITER $$
create procedure sp_Eliminar_Empresa(in codigoE int)
BEGIN
delete from Empresa where CodigoEmpresa=codigoE;
END $$
DELIMITER ;
-- Buscar
DELIMITER $$
create procedure sp_Buscar_Empresa(in codigoE int)
BEGIN
Select * from Empresa where CodigoEmpresa=codigoE;
END $$
DELIMITER ;
-- Buscar por nombre
/*DELIMITER $$
create procedure sp_Buscar_Empresa_Nombre(in nombreE varchar(150))
BEGIN
Select * from Empresa e where (e.codigoEmpresa LIKE concat(nombreE,'%') OR e.nombreEmpresa LIKE concat(nombreE,'%'));
END $$
DELIMITER ;*/
-- -------------- Tabla Presupuesto--------------
-- Agregar
DELIMITER $$
create procedure sp_Agregar_Presupuesto(in fechaS date, cantidadP decimal(10,2), codigoE int)
BEGIN
insert into Presupuesto(Fecha_Solicitud,CantidadPresupuesto,CodigoEmpresa) values(fechaS,cantidadP,codigoE);
END $$
DELIMITER ;
-- Listar
DELIMITER $$
create procedure sp_Listar_Presupuesto()
BEGIN
Select * from Presupuesto;
END $$
DELIMITER ;
-- Actualizar
DELIMITER $$
create procedure sp_Actualizar_Presupuesto(in codP int, fechaS date, cantidadP decimal(10,2))
BEGIN
update Presupuesto set Fecha_Solicitud=fechaS, CantidadPresupuesto=cantidadP where CodigoPresupuesto=codP;
END $$
DELIMITER ;
-- Eliminar
DELIMITER $$
create procedure sp_Eliminar_Presupuesto(in codP int)
BEGIN
delete from Presupuesto where CodigoPresupuesto=codP;
END $$
DELIMITER ;
-- Buscar
DELIMITER $$
create procedure sp_Buscar_Presupuesto(in codP int)
BEGIN
Select * from Presupuesto where CodigoPresupuesto=codP;
END $$
DELIMITER ;
-- -------------- Tabla Servicio--------------
-- Agregar
DELIMITER $$
create procedure sp_Agregar_Servicio(in fechaS date, tipoS varchar(100), horaS time, lugarS varchar(100), telefonoC varchar(10), codiE int)
BEGIN
insert into Servicio(Fecha_Servicio,Tipo_Servicio,HoraServicio,LugarServicio,TelefonoContacto,CodigoEmpresa) values(fechaS,tipoS,horaS,lugarS,telefonoC,codiE);
END $$
DELIMITER ;
-- Listar
DELIMITER $$
create procedure sp_Listar_Servicio()
BEGIN
Select * from Servicio;
END $$
DELIMITER ;
-- Actualizar
DELIMITER $$
create procedure sp_Actualizar_Servicio(in codS int, fechaS date, tipoS varchar(100), horaS time, lugarS varchar(100), telefonoC varchar(10))
BEGIN
update Servicio set Fecha_Servicio=fechaS, Tipo_Servicio=tipoS, HoraServicio=horaS, LugarServicio=lugarS, TelefonoContacto=telefonoC
where CodigoServicio=codS;
END $$
DELIMITER ;
-- Eliminar
DELIMITER $$
create procedure sp_Eliminar_Servicio(in codS int)
BEGIN
delete from Servicio where CodigoServicio=codS;
END $$
DELIMITER ;
-- Buscar
DELIMITER $$
create procedure sp_Buscar_Servicio(in codS int)
BEGIN
Select * from Servicio where CodigoServicio=codS;
END $$
DELIMITER ;
-- -------------- Tabla Servicio_Has_Empleado--------------
-- Agregar
DELIMITER $$
create procedure sp_Agregar_ServicioHasEmpleado( in codigoServicioP int, in codigoEmpleadoP int, in fechaP date, in horaP time, in lugarP varchar(150) )
BEGIN
insert into servicio_has_empleado(codigoServicio, codigoEmpleado, fechaEvento, horaEvento, lugarEvento) values (codigoServicioP, codigoEmpleadoP, fechaP, horaP, lugarP);
END $$
DELIMITER ;
-- Listar
DELIMITER $$
create procedure sp_Listar_Servicio_has_Empleado()
BEGIN
Select * from Servicio_Has_Empleado;
END $$
DELIMITER ;
-- Actualizar
DELIMITER $$
create procedure sp_Actualizar_ServicioHasEmpleado(in servicios_codigoP int, in fechaP date, in horaP time, in lugarP varchar(50))
BEGIN
update servicio_has_empleado set fechaEvento=fechaP, horaEvento=horaP, lugarEvento=lugarP where Servicios_codigoServicio=servicios_codigoP;
END $$
DELIMITER ;
-- Eliminar
DELIMITER $$
create procedure sp_Eliminar_ServicioHasEmpleado(in codP int)
BEGIN
delete from servicio_has_empleado where Servicios_codigoServicio=codP;
END $$
DELIMITER ;
-- Buscar
DELIMITER $$
create procedure sp_Buscar_ServicioHasEmpleado(in codP int)
BEGIN
select * from servicio_has_empleado where Servicios_codigoServicio=codP;
END $$
DELIMITER ;
-- -------------- Tabla Plato--------------
-- Agregar
DELIMITER $$
create procedure sp_Agregar_Plato(in cantidadP int, nombreP varchar(50), descripcionP varchar(150), precipP decimal(10,2), codTP int)
BEGIN
insert into Plato(Cantidad,NombrePlato,DescripcionPlato,PrecioPlato,CodigoTipoPlato) values(cantidadP,nombreP,descripcionP,precipP,codTP);
END $$
DELIMITER ;
-- Listar
DELIMITER $$
create procedure sp_Listar_Plato()
BEGIN
Select * from Plato;
END $$
DELIMITER ;
-- Actualizar
DELIMITER $$
create procedure sp_Actualizar_Plato(in codP int, cantidadP int, nombreP varchar(50), descripcionP varchar(150), precioP decimal(10,2))
BEGIN
update Plato set Cantidad=cantidadP, NombrePlato=nombreP, DescripcionPlato=descripcionP, PrecioPlato=precioP
where CodigoPlato=codP;
END $$
DELIMITER ;
-- Eliminar
DELIMITER $$
create procedure sp_Eliminar_Plato(in codP int)
BEGIN
delete from Plato where CodigoPlato=codP;
END $$
DELIMITER ;
-- Buscar
DELIMITER $$
create procedure sp_Buscar_Plato(in codP int)
BEGIN
Select * from Plato where CodigoPlato=codP;
END $$
DELIMITER ;
-- -------------- Tabla Producto_Has_Plato--------------
/*
-- Agregar
DELIMITER $$
create procedure sp_Agregar_Producto_has_Plato(in Producto_codP int, platos_codP int)
BEGIN
insert into producto_has_plato(Producto_codigoProducto,Platos_codigoPlato) values(Producto_codP,platos_codP);
END $$
DELIMITER ;*/
-- Listar
DELIMITER $$
create procedure sp_Listar_Producto_has_Plato()
BEGIN
Select P.codigoProducto, pL.codigoPlato from Producto P inner join Plato pL;
END $$
DELIMITER ;
-- -------------- Tabla Servicio_Has_Plato--------------
/*
-- Agregar
DELIMITER $$
create procedure sp_Agregar_Servicio_has_Plato(in serv_codP int, platos_codP int)
BEGIN
insert into servicio_has_Plato(Servicios_codigoServicio,Platos_codigoPlato) values(serv_codP,platos_codP);
END $$
DELIMITER ;*/
-- Listar
DELIMITER $$
create procedure sp_Listar_Servicio_has_Plato()
BEGIN
select S.codigoServicio as codigoServicio, P.codigoPlato as codigoPlato from Servicio S inner join Plato P;
END $$
DELIMITER ;
-- Insertando datos a tabla Empresa
call sp_Listar_Empresa();
call sp_Agregar_Empresa('Diana','Direccion 1','12345678');
call sp_Agregar_Empresa('mytec','Direccion 2','87456321');
call sp_Agregar_Empresa('Imeqmo','Direccion 3','11111111');
call sp_Agregar_Empresa('LuzGO','Direccion 4','52525252');
call sp_Agregar_Empresa('MaxE','Direccion 5','66998877');
call sp_Agregar_Empresa('LeoPR','Direccion 6','11445566');
call sp_Agregar_Empresa('FireX','Direccion 7','77888552');
call sp_Agregar_Empresa('Xinx','Direccion 8','24589874');
call sp_Agregar_Empresa('JD','Direccion 9','45674844');
call sp_Agregar_Empresa('HELE','Direccion 10','25415455');
call sp_Agregar_Empresa('MRLO','Direccion 11','24574875');
-- Insertando datos a tabla TipoEmpleado
call sp_Listar_TipoEmpleado();
call sp_Agregar_TipoEmpleado('Mesero');
call sp_Agregar_TipoEmpleado('Chef');
call sp_Agregar_TipoEmpleado('Catador');
call sp_Agregar_TipoEmpleado('Ayudante de camarero');
call sp_Agregar_TipoEmpleado('Maitre');
call sp_Agregar_TipoEmpleado('Gourmet');
call sp_Agregar_TipoEmpleado('Hostess');
call sp_Agregar_TipoEmpleado('Cocinero');
-- Insertando datos a tabla Presupuesto
call sp_Listar_Presupuesto();
call sp_Agregar_Presupuesto('2020-02-10',15000,2);
call sp_Agregar_Presupuesto('2020-01-02',2050,1);
call sp_Agregar_Presupuesto('2018-02-18',10000,6);
call sp_Agregar_Presupuesto('2019-08-28',6085.75,8);
call sp_Agregar_Presupuesto('2020-05-05',12000,9);
call sp_Agregar_Presupuesto('2020-06-20',11100,10);
call sp_Agregar_Presupuesto('2020-02-15',15900,3);
call sp_Agregar_Presupuesto('2019-12-29',7800,2);
call sp_Agregar_Presupuesto('2015-07-13',13042,7);
call sp_Agregar_Presupuesto('2019-09-08',14245.80,4);
call sp_Agregar_Presupuesto('2017-12-26',1508.50,11);
-- Insertando datos a tabla Empleado
call sp_Listar_Empleado();
call sp_Agregar_Empleado(01,'Perez','Juan','zona 12','12345678',1,2);
call sp_Agregar_Empleado(02,'Lopez','Leonel','zona 8','78964565',4,4);
call sp_Agregar_Empleado(03,'Hernandez','Javier','zona 1','41567896',6,7);
call sp_Agregar_Empleado(04,'Herrarte','Angel','zona 2','23569878',9,8);
call sp_Agregar_Empleado(05,'Jose','Gongora','zona 6','45789632',10,5);
-- Insertando datos a tabla Servicio
call sp_Listar_Servicio();
call sp_Agregar_Servicio('2020-06-16','Completo','12:00:00','Zona 4','45674899',9);
call sp_Agregar_Servicio('2020-01-10','Bufette','15:30:00','Zona 10','52525200',4);
call sp_Agregar_Servicio('2019-05-14','Completo','11:00:00','Zona 15','25415455',10);
call sp_Agregar_Servicio('2018-08-28','Completo','16:45:00','Zona 11','24574875',11);
call sp_Agregar_Servicio('2020-02-6','Banquete','21:05:00','Zona 6','24589878',8);
call sp_Agregar_Servicio('2017-08-6','Cena','18:30:00','Zona 15','12345678',2);
call sp_Agregar_Servicio('2020-03-14','Buffete','12:30:00','Ciudad de Guatemala','41167854',2);
-- Insertando datos a tabla Tipo_Plato
call sp_Listar_Tipo_Plato();
call sp_Agregar_Tipo_Plato('Italiano');
call sp_Agregar_Tipo_Plato('Mexicano');
call sp_Agregar_Tipo_Plato('Mediterraneo');
call sp_Agregar_Tipo_Plato('Francesa');
call sp_Agregar_Tipo_Plato('Postre');
call sp_Agregar_Tipo_Plato("Tipico");
call sp_Agregar_Tipo_Plato("Entrada");
call sp_Agregar_Tipo_Plato("Oriental");
-- Insertando datos a tabla Producto
call sp_Listar_Producto();
call sp_Agregar_Producto('Huevo',300);
call sp_Agregar_Producto('Filete',200);
call sp_Agregar_Producto('Pasta',150);
call sp_Agregar_Producto('Albondigas',258);
call sp_Agregar_Producto('Lechuga',500);
call sp_Agregar_Producto('Pan',550);
call sp_Agregar_Producto('Leche',150);
call sp_Agregar_Producto('Harina',250);
call sp_Agregar_Producto('Zanahorias',400);
call sp_Agregar_Producto('Tostadas',500);
-- Insertando datos a tabla Plato
call sp_Listar_Plato();
call sp_Agregar_Plato(100,'Sabrons','Rico plato de sopa',50.50,2);
call sp_Agregar_Plato(180,'Pastel Tres Leches','Rico postre muy jugoso',75.75,6);
call sp_Agregar_Plato(50,'Hilachas','Receta de Baja Verapaz',45.75,7);
call sp_Agregar_Plato(250,'Pastel de zanahorias','Esponjosos y repletos de aromáticos sabores de cardamomo y canela',84,6);
call sp_Agregar_Plato(152,'Rollitos de primavera ligeros','Sin frituras que están igual de buenos que los fritos',50,8);
call sp_Agregar_Plato(500,'Espagueti negro con langostinos','Servimos los espaguetis negros con langostinos, bien calientes y recién hechos',60.25,2);
call sp_Agregar_Plato(150,'Enchiladas de carne','Ricas enchiladas con tortillas de trigo',39.99,3);
-- Insertando datos a tabla Servicios_Has_Empleados
call sp_Listar_Servicio_has_Empleado();
call sp_Agregar_ServiciohasEmpleado(1,1,'2020-02-22','10:55:00','Zona 10');
call sp_Agregar_ServiciohasEmpleado(2,2,'2020-04-02','14:30:00','Zona 2');
call sp_Agregar_ServiciohasEmpleado(3,4,'2010-02-12','15:00:00','Zona 15');
call sp_Agregar_ServiciohasEmpleado(4,4,'2018-07-25','16:25:00','Zona 6');
call sp_Agregar_ServiciohasEmpleado(5,5,'2019-08-28','12:00:00','Zona 1'); |
CREATE TABLE `address` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`city` text,
`state` text,
`person_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `person_id` (`person_id`),
CONSTRAINT `address_ibfk_1` FOREIGN KEY (`person_id`) REFERENCES `person` (`id`) ON DELETE CASCADE
); |
SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS `product_additional_information`;
DROP TABLE IF EXISTS `folder_additional_information`;
DROP TABLE IF EXISTS `category_additional_information`;
DROP TABLE IF EXISTS `content_additional_information`;
DROP TABLE IF EXISTS `product_additional_information_i18n`;
DROP TABLE IF EXISTS `folder_additional_information_i18n`;
DROP TABLE IF EXISTS `category_additional_information_i18n`;
DROP TABLE IF EXISTS `content_additional_information_i18n`;
SET FOREIGN_KEY_CHECKS = 1;
|
select
distinct rl.lang_name as "Language",
--count(distinct r.name) as "Repositories (names)",
count(distinct r.alias) as "Repositories",
--sum(rl.lang_loc) as "LOC (non distinct)",
-- sum(distinct rl.lang_loc) as "LOC distinct"
sum(rl.lang_loc) as "LOC"
--r.id as "Repository ID",
--r.name as "Repository name",
--r.alias as "Repository alias",
--rl.lang_loc as "LOC"
from
gha_repos r,
gha_repos_langs rl
where
r.name = rl.repo_name
and rl.lang_name is not null and rl.lang_name not in ('', 'unknown')
and (r.name, r.id) = (
select i.name,
i.id
from
gha_repos i
where
i.alias = r.alias
and i.name like '%_/_%'
and i.name not like '%/%/%'
limit 1
)
group by
rl.lang_name
order by
"LOC" desc
|
/*
student 테이블에서 insert 이벤트가 발생하면 추가된 student_num의 정보를 이용하여
graduation 테이블에 insert를 한다.
*/
use university;
drop trigger if exists insert_student;
delimiter //
create trigger insert_student
after insert on student
for each row
begin
declare r_num int;
declare r_year int;
/* 졸업 요건 정보는 입학년도와 전공을 통해 결정된다는 전제조건 */
set r_year = new.student_num / 1000000; -- 졸업 연도 계산
if new.student_major is not null then
set r_num = (select requirement_num from requirement where
new.student_major = requirement_major and requirement_entrance_year = r_year);
end if;
insert graduation(graduation_student_num,graduation_requirement_num)
values(new.student_num, r_num);
end //
delimiter ;
|
---------------------------------------------------
-- AICG
-- Snowflake Carolinas Meetup
-- 20210920
-- TOPIC: Snowflake Streams - Continuous Data Pipeline
---------------------------------------------------
-- switch to the context of database, wh, role
use role datalakehouse_role;
use database demo_db;
use warehouse datalakehouse_wh;
-- // Create our new schema
create schema IF NOT EXISTS MEETUP_DB_20210920;
-- // Yes, land data to this table via insert / files / Kafka / SnowPipe
create or replace table w_customer_stage (
id int,
customer_name string,
customer_address string,
customer_postal_code string
);
INSERT INTO w_customer_stage (id, customer_name, customer_address, customer_postal_code)
VALUES
( 1, 'John Conoor', '345 Baker St.', 90210),
( 2, 'Sarah Conoor', '16 Penetentary Drive', 90210)
;
-- verify the table has data
SELECT * FROM w_customer_stage;
-- // This is the target table for merge
create or replace table w_customer_dimension (
id int,
customer_name string,
customer_address string,
customer_postal_code string,
modified_ts datetime default current_timestamp
);
-- verify the table has data
SELECT * FROM w_customer_dimension;
-- // depending on the access you may not have create stage, so perhaps switch to a role with access
use role datalakehouse_role;
-- // Create a stream, and use properties such as append_only if interested only in inserts;
--
create or replace stream customer_stage_stream_inserts on table w_customer_stage append_only = true;
create or replace stream customer_stage_stream_updates on table w_customer_stage;
SHOW streams;
-- //reference and discussion point for checking for records in stream if not using append_only
--where metadata$action = 'DELETE';
-- verify the table has data
SELECT * FROM w_customer_dimension;
INSERT INTO w_customer_stage (id, customer_name, customer_address, customer_postal_code)
VALUES
( 3, 'Chales Dyson', '321 Ocean View Dr..', 90210),
( 4, 'Dr. Peter Silberman', '1PP Police Plaza', 90210)
;
-- // Periodic merge from staging using CDC. Covers updates & inserts
create task customer_stage_stream_to_rtv_dimension
warehouse = datalakehouse_wh
schedule = '2 minutes'
as
merge into w_customer_dimension pd
using
customer_stage_stream_inserts delta
on pd.id = delta.id
when matched then
update
set pd.customer_name = delta.customer_name, pd.customer_address = delta.customer_address, pd.customer_postal_code = delta.customer_postal_code
when not matched then
insert (id, customer_name, customer_address, customer_postal_code)
values (delta.id, delta.customer_name, delta.customer_address, delta.customer_postal_code)
;
--// let's see the condition of the task and if it was created
SHOW TASKS;
-- resume the task then go to the next step after waiting 2-3 minutes, since tasks are created in suspended
ALTER TASK customer_stage_stream_to_rtv_dimension RESUME;
-- verify the table has data now after the stage data was pulled via the task
SELECT * FROM w_customer_stage;
-- we should see data here
SELECT * FROM w_customer_dimension;
INSERT INTO w_customer_stage (id, customer_name, customer_address, customer_postal_code)
VALUES
( 5, 'Chales Dyson Jr.', '321 Ocean View Dr XX.', 90210),
( 6, 'Dr. Peter Silberman Jr.', '1PP Police Plaza XX', 90210)
;
UPDATE w_customer_stage
set customer_name = 'Updated Name'
where id = 2
;
-- // get from the stream
select * from customer_stage_stream_inserts;
select * from customer_stage_stream_updates WHERE METADATA$ISUPDATE = TRUE;
INSERT INTO w_customer_stage (id, customer_name, customer_address, customer_postal_code)
VALUES
( 7, 'Chales Dyson III.', '321 Ocean View Dr XX.', 90210),
( 8, 'Dr. Peter Silberman III', '1PP Police Plaza XX', 90210)
;
UPDATE w_customer_stage
set customer_name = 'Updated Name 3'
where id = 3
;
-- understanding transaction timing... for statements inside of a begin...commit;
--//Cleanup Script
DROP task customer_stage_stream_to_rtv_dimension;
DROP table w_customer_dimension;
DROP table w_customer_stage;
|
--Intro to DML
--READ
--selecting all the elements from table_a
--SELECT <rows> FROM <table-name>
select * from table_a;
select * from fruits;
select fruit_name, description from fruits;
--create
--Adding rows/records to the table
-- INSERT INTO <table-name> VALUES (...)
insert into fruits values (1,'Dragon Fruit','Dissapointing',false);
insert into fruits (fruit_id,tasty) values (27,false);
insert
into
fruits (fruit_id, fruit_name, description, tasty)
values
(1,'Dragon Fruit','Dissapointing',false),
(2, 'Banana','Is yellow', true),
(3, 'Apple', 'Is red', true),
(4, 'Orange','Is orange', true);
--UPDATE
update fruits set tasty = false where fruit_id = 4;
update fruits set tasty = true where tasty = false;
--DELETE
delete from fruits where fruit_id = 1;
delete from fruits where fruit_name = 'Orange';
|
ALTER TABLE `m_loan_transaction` ADD `submitted_on_date` DATE NOT NULL;
UPDATE `m_loan_transaction` SET `submitted_on_date`= `transaction_date` ;
|
CREATE DATABASE priceapp_db;
USE priceapp_db;
CREATE TABLE `priceapp_db`.`product` (
`id` INT NOT NULL AUTO_INCREMENT,
`code` VARCHAR(50) NOT NULL,
`name` VARCHAR(255) NOT NULL,
`carton_size` INT NULL DEFAULT NULL,
`carton_price` DECIMAL(10,2) NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `code_UNIQUE` (`code` ASC));
INSERT INTO `priceapp_db`.`product` (`id`, `code`, `name`, `carton_size`, `carton_price`) VALUES ('1', 'C001', 'Penguin-ears', '20', '175');
INSERT INTO `priceapp_db`.`product` (`id`, `code`, `name`, `carton_size`, `carton_price`) VALUES ('2', 'C002', 'Horseshoe', '5', '825'); |
-- phpMyAdmin SQL Dump
-- version 4.2.11
-- http://www.phpmyadmin.net
--
-- Servidor: localhost
-- Tiempo de generación: 18-11-2015 a las 03:47:12
-- Versión del servidor: 5.6.21
-- Versión de PHP: 5.6.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Base de datos: `inmobiliaria`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `departamento`
--
CREATE TABLE IF NOT EXISTS `departamento` (
`id` int(11) NOT NULL,
`valor` varchar(40) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `departamento`
--
INSERT INTO `departamento` (`id`, `valor`) VALUES
(1, 'AMAZONAS'),
(2, 'ANTIOQUIA'),
(3, 'ARAUCA'),
(4, 'ATLÁNTICO'),
(5, 'BOLÍVAR'),
(6, 'BOYACÁ'),
(7, 'CALDAS'),
(8, 'CAQUETÁ'),
(9, 'CASANARE'),
(10, 'CAUCA'),
(11, 'CESAR'),
(12, 'CHOCÓ'),
(13, 'CÓRDOBA'),
(14, 'CUNDINAMARCA'),
(15, 'GUAINÍA'),
(16, 'GUAVIARE'),
(17, 'HUILA'),
(18, 'LA GUAJIRA'),
(19, 'MAGDALENA'),
(20, 'META'),
(21, 'NARIÑO'),
(22, 'NORTE DE SANTANDER'),
(23, 'PUTUMAYO'),
(24, 'QUINDÍO'),
(25, 'RISARALDA'),
(26, 'SAN ANDRÉS Y ROVIDENCIA'),
(27, 'SANTANDER'),
(28, 'SUCRE'),
(29, 'TOLIMA'),
(30, 'VALLE DEL CAUCA'),
(31, 'VAUPÉS'),
(32, 'VICHADA');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `municipio`
--
CREATE TABLE IF NOT EXISTS `municipio` (
`id` int(11) NOT NULL,
`valor` varchar(40) NOT NULL,
`departamento` int(3) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1113 DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `municipio`
--
INSERT INTO `municipio` (`id`, `valor`, `departamento`) VALUES
(1, 'EL ENCANTO', 1),
(2, 'LA CHORRERA', 1),
(3, 'LA PEDRERA', 1),
(4, 'LA VICTORIA', 1),
(5, 'LETICIA', 1),
(6, 'MIRITI', 1),
(7, 'PUERTO ALEGRIA', 1),
(8, 'PUERTO ARICA', 1),
(9, 'PUERTO NARIÑO', 1),
(10, 'PUERTO SANTANDER', 1),
(11, 'TURAPACA', 1),
(12, 'ABEJORRAL', 2),
(13, 'ABRIAQUI', 2),
(14, 'ALEJANDRIA', 2),
(15, 'AMAGA', 2),
(16, 'AMALFI', 2),
(17, 'ANDES', 2),
(18, 'ANGELOPOLIS', 2),
(19, 'ANGOSTURA', 2),
(20, 'ANORI', 2),
(21, 'ANTIOQUIA', 2),
(22, 'ANZA', 2),
(23, 'APARTADO', 2),
(24, 'ARBOLETES', 2),
(25, 'ARGELIA', 2),
(26, 'ARMENIA', 2),
(27, 'BARBOSA', 2),
(28, 'BELLO', 2),
(29, 'BELMIRA', 2),
(30, 'BETANIA', 2),
(31, 'BETULIA', 2),
(32, 'BOLIVAR', 2),
(33, 'BRICEÑO', 2),
(34, 'BURITICA', 2),
(35, 'CACERES', 2),
(36, 'CAICEDO', 2),
(37, 'CALDAS', 2),
(38, 'CAMPAMENTO', 2),
(39, 'CANASGORDAS', 2),
(40, 'CARACOLI', 2),
(41, 'CARAMANTA', 2),
(42, 'CAREPA', 2),
(43, 'CARMEN DE VIBORAL', 2),
(44, 'CAROLINA DEL PRINCIPE', 2),
(45, 'CAUCASIA', 2),
(46, 'CHIGORODO', 2),
(47, 'CISNEROS', 2),
(48, 'COCORNA', 2),
(49, 'CONCEPCION', 2),
(50, 'CONCORDIA', 2),
(51, 'COPACABANA', 2),
(52, 'DABEIBA', 2),
(53, 'DONMATIAS', 2),
(54, 'EBEJICO', 2),
(55, 'EL BAGRE', 2),
(56, 'EL PENOL', 2),
(57, 'EL RETIRO', 2),
(58, 'ENTRERRIOS', 2),
(59, 'ENVIGADO', 2),
(60, 'FREDONIA', 2),
(61, 'FRONTINO', 2),
(62, 'GIRALDO', 2),
(63, 'GIRARDOTA', 2),
(64, 'GOMEZ PLATA', 2),
(65, 'GRANADA', 2),
(66, 'GUADALUPE', 2),
(67, 'GUARNE', 2),
(68, 'GUATAQUE', 2),
(69, 'HELICONIA', 2),
(70, 'HISPANIA', 2),
(71, 'ITAGUI', 2),
(72, 'ITUANGO', 2),
(73, 'JARDIN', 2),
(74, 'JERICO', 2),
(75, 'LA CEJA', 2),
(76, 'LA ESTRELLA', 2),
(77, 'LA PINTADA', 2),
(78, 'LA UNION', 2),
(79, 'LIBORINA', 2),
(80, 'MACEO', 2),
(81, 'MARINILLA', 2),
(82, 'MEDELLIN', 2),
(83, 'MONTEBELLO', 2),
(84, 'MURINDO', 2),
(85, 'MUTATA', 2),
(86, 'NARINO', 2),
(87, 'NECHI', 2),
(88, 'NECOCLI', 2),
(89, 'OLAYA', 2),
(90, 'PEQUE', 2),
(91, 'PUEBLORRICO', 2),
(92, 'PUERTO BERRIO', 2),
(93, 'PUERTO NARE', 2),
(94, 'PUERTO TRIUNFO', 2),
(95, 'REMEDIOS', 2),
(96, 'RIONEGRO', 2),
(97, 'SABANALARGA', 2),
(98, 'SABANETA', 2),
(99, 'SALGAR', 2),
(100, 'SAN ANDRES DE CUERQUIA', 2),
(101, 'SAN CARLOS', 2),
(102, 'SAN FRANCISCO', 2),
(103, 'SAN JERONIMO', 2),
(104, 'SAN JOSE DE LA MONTAÑA', 2),
(105, 'SAN JUAN DE URABA', 2),
(106, 'SAN LUIS', 2),
(107, 'SAN PEDRO DE LOS MILAGROS', 2),
(108, 'SAN PEDRO DE URABA', 2),
(109, 'SAN RAFAEL', 2),
(110, 'SAN ROQUE', 2),
(111, 'SAN VICENTE', 2),
(112, 'SANTA BARBARA', 2),
(113, 'SANTA ROSA DE OSOS', 2),
(114, 'SANTO DOMINGO', 2),
(115, 'SANTUARIO', 2),
(116, 'SEGOVIA', 2),
(117, 'SONSON', 2),
(118, 'SOPETRAN', 2),
(119, 'TAMESIS', 2),
(120, 'TARAZA', 2),
(121, 'TARSO', 2),
(122, 'TITIRIBI', 2),
(123, 'TOLEDO', 2),
(124, 'TURBO', 2),
(125, 'URAMITA', 2),
(126, 'URRAO', 2),
(127, 'VALDIVIA', 2),
(128, 'VALPARAISO', 2),
(129, 'VEGACHI', 2),
(130, 'VENECIA', 2),
(131, 'VIGIA DEL FUERTE', 2),
(132, 'YALI', 2),
(133, 'YARUMAL', 2),
(134, 'YOLOMBO', 2),
(135, 'YONDO', 2),
(136, 'ZARAGOZA', 2),
(137, 'ARAUCA', 3),
(138, 'ARAUQUITA', 3),
(139, 'CRAVO NORTE', 3),
(140, 'FORTUL', 3),
(141, 'PUERTO RONDON', 3),
(142, 'SARAVENA', 3),
(143, 'TAME', 3),
(144, 'BARANOA', 4),
(145, 'BARRANQUILLA', 4),
(146, 'CAMPO DE LA CRUZ', 4),
(147, 'CANDELARIA', 4),
(148, 'GALAPA', 4),
(149, 'JUAN DE ACOSTA', 4),
(150, 'LURUACO', 4),
(151, 'MALAMBO', 4),
(152, 'MANATI', 4),
(153, 'PALMAR DE VARELA', 4),
(154, 'PIOJO', 4),
(155, 'POLO NUEVO', 4),
(156, 'PONEDERA', 4),
(157, 'PUERTO COLOMBIA', 4),
(158, 'REPELON', 4),
(159, 'SABANAGRANDE', 4),
(160, 'SABANALARGA', 4),
(161, 'SANTA LUCIA', 4),
(162, 'SANTO TOMAS', 4),
(163, 'SOLEDAD', 4),
(164, 'SUAN', 4),
(165, 'TUBARA', 4),
(166, 'USIACURI', 4),
(167, 'ACHI', 5),
(168, 'ALTOS DEL ROSARIO', 5),
(169, 'ARENAL', 5),
(170, 'ARJONA', 5),
(171, 'ARROYOHONDO', 5),
(172, 'BARRANCO DE LOBA', 5),
(173, 'BRAZUELO DE PAPAYAL', 5),
(174, 'CALAMAR', 5),
(175, 'CANTAGALLO', 5),
(176, 'CARTAGENA DE INDIAS', 5),
(177, 'CICUCO', 5),
(178, 'CLEMENCIA', 5),
(179, 'CORDOBA', 5),
(180, 'EL CARMEN DE BOLIVAR', 5),
(181, 'EL GUAMO', 5),
(182, 'EL PENION', 5),
(183, 'HATILLO DE LOBA', 5),
(184, 'MAGANGUE', 5),
(185, 'MAHATES', 5),
(186, 'MARGARITA', 5),
(187, 'MARIA LA BAJA', 5),
(188, 'MONTECRISTO', 5),
(189, 'MORALES', 5),
(190, 'MORALES', 5),
(191, 'NOROSI', 5),
(192, 'PINILLOS', 5),
(193, 'REGIDOR', 5),
(194, 'RIO VIEJO', 5),
(195, 'SAN CRISTOBAL', 5),
(196, 'SAN ESTANISLAO', 5),
(197, 'SAN FERNANDO', 5),
(198, 'SAN JACINTO', 5),
(199, 'SAN JACINTO DEL CAUCA', 5),
(200, 'SAN JUAN DE NEPOMUCENO', 5),
(201, 'SAN MARTIN DE LOBA', 5),
(202, 'SAN PABLO', 5),
(203, 'SAN PABLO NORTE', 5),
(204, 'SANTA CATALINA', 5),
(205, 'SANTA CRUZ DE MOMPOX', 5),
(206, 'SANTA ROSA', 5),
(207, 'SANTA ROSA DEL SUR', 5),
(208, 'SIMITI', 5),
(209, 'SOPLAVIENTO', 5),
(210, 'TALAIGUA NUEVO', 5),
(211, 'TUQUISIO', 5),
(212, 'TURBACO', 5),
(213, 'TURBANA', 5),
(214, 'VILLANUEVA', 5),
(215, 'ZAMBRANO', 5),
(216, 'AQUITANIA', 6),
(217, 'ARCABUCO', 6),
(218, 'BELÉN', 6),
(219, 'BERBEO', 6),
(220, 'BETÉITIVA', 6),
(221, 'BOAVITA', 6),
(222, 'BOYACÁ', 6),
(223, 'BRICEÑO', 6),
(224, 'BUENAVISTA', 6),
(225, 'BUSBANZÁ', 6),
(226, 'CALDAS', 6),
(227, 'CAMPO HERMOSO', 6),
(228, 'CERINZA', 6),
(229, 'CHINAVITA', 6),
(230, 'CHIQUINQUIRÁ', 6),
(231, 'CHÍQUIZA', 6),
(232, 'CHISCAS', 6),
(233, 'CHITA', 6),
(234, 'CHITARAQUE', 6),
(235, 'CHIVATÁ', 6),
(236, 'CIÉNEGA', 6),
(237, 'CÓMBITA', 6),
(238, 'COPER', 6),
(239, 'CORRALES', 6),
(240, 'COVARACHÍA', 6),
(241, 'CUBARA', 6),
(242, 'CUCAITA', 6),
(243, 'CUITIVA', 6),
(244, 'DUITAMA', 6),
(245, 'EL COCUY', 6),
(246, 'EL ESPINO', 6),
(247, 'FIRAVITOBA', 6),
(248, 'FLORESTA', 6),
(249, 'GACHANTIVÁ', 6),
(250, 'GÁMEZA', 6),
(251, 'GARAGOA', 6),
(252, 'GUACAMAYAS', 6),
(253, 'GÜICÁN', 6),
(254, 'IZA', 6),
(255, 'JENESANO', 6),
(256, 'JERICÓ', 6),
(257, 'LA UVITA', 6),
(258, 'LA VICTORIA', 6),
(259, 'LABRANZA GRANDE', 6),
(260, 'MACANAL', 6),
(261, 'MARIPÍ', 6),
(262, 'MIRAFLORES', 6),
(263, 'MONGUA', 6),
(264, 'MONGUÍ', 6),
(265, 'MONIQUIRÁ', 6),
(266, 'MOTAVITA', 6),
(267, 'MUZO', 6),
(268, 'NOBSA', 6),
(269, 'NUEVO COLÓN', 6),
(270, 'OICATÁ', 6),
(271, 'OTANCHE', 6),
(272, 'PACHAVITA', 6),
(273, 'PÁEZ', 6),
(274, 'PAIPA', 6),
(275, 'PAJARITO', 6),
(276, 'PANQUEBA', 6),
(277, 'PAUNA', 6),
(278, 'PAYA', 6),
(279, 'PAZ DE RÍO', 6),
(280, 'PESCA', 6),
(281, 'PISBA', 6),
(282, 'PUERTO BOYACA', 6),
(283, 'QUÍPAMA', 6),
(284, 'RAMIRIQUÍ', 6),
(285, 'RÁQUIRA', 6),
(286, 'RONDÓN', 6),
(287, 'SABOYÁ', 6),
(288, 'SÁCHICA', 6),
(289, 'SAMACÁ', 6),
(290, 'SAN EDUARDO', 6),
(291, 'SAN JOSÉ DE PARE', 6),
(292, 'SAN LUÍS DE GACENO', 6),
(293, 'SAN MATEO', 6),
(294, 'SAN MIGUEL DE SEMA', 6),
(295, 'SAN PABLO DE BORBUR', 6),
(296, 'SANTA MARÍA', 6),
(297, 'SANTA ROSA DE VITERBO', 6),
(298, 'SANTA SOFÍA', 6),
(299, 'SANTANA', 6),
(300, 'SATIVANORTE', 6),
(301, 'SATIVASUR', 6),
(302, 'SIACHOQUE', 6),
(303, 'SOATÁ', 6),
(304, 'SOCHA', 6),
(305, 'SOCOTÁ', 6),
(306, 'SOGAMOSO', 6),
(307, 'SORA', 6),
(308, 'SORACÁ', 6),
(309, 'SOTAQUIRÁ', 6),
(310, 'SUSACÓN', 6),
(311, 'SUTARMACHÁN', 6),
(312, 'TASCO', 6),
(313, 'TIBANÁ', 6),
(314, 'TIBASOSA', 6),
(315, 'TINJACÁ', 6),
(316, 'TIPACOQUE', 6),
(317, 'TOCA', 6),
(318, 'TOGÜÍ', 6),
(319, 'TÓPAGA', 6),
(320, 'TOTA', 6),
(321, 'TUNJA', 6),
(322, 'TUNUNGUÁ', 6),
(323, 'TURMEQUÉ', 6),
(324, 'TUTA', 6),
(325, 'TUTAZÁ', 6),
(326, 'UMBITA', 6),
(327, 'VENTA QUEMADA', 6),
(328, 'VILLA DE LEYVA', 6),
(329, 'VIRACACHÁ', 6),
(330, 'ZETAQUIRA', 6),
(331, 'AGUADAS', 7),
(332, 'ANSERMA', 7),
(333, 'ARANZAZU', 7),
(334, 'BELALCAZAR', 7),
(335, 'CHINCHINÁ', 7),
(336, 'FILADELFIA', 7),
(337, 'LA DORADA', 7),
(338, 'LA MERCED', 7),
(339, 'MANIZALES', 7),
(340, 'MANZANARES', 7),
(341, 'MARMATO', 7),
(342, 'MARQUETALIA', 7),
(343, 'MARULANDA', 7),
(344, 'NEIRA', 7),
(345, 'NORCASIA', 7),
(346, 'PACORA', 7),
(347, 'PALESTINA', 7),
(348, 'PENSILVANIA', 7),
(349, 'RIOSUCIO', 7),
(350, 'RISARALDA', 7),
(351, 'SALAMINA', 7),
(352, 'SAMANA', 7),
(353, 'SAN JOSE', 7),
(354, 'SUPÍA', 7),
(355, 'VICTORIA', 7),
(356, 'VILLAMARÍA', 7),
(357, 'VITERBO', 7),
(358, 'ALBANIA', 8),
(359, 'BELÉN ANDAQUIES', 8),
(360, 'CARTAGENA DEL CHAIRA', 8),
(361, 'CURILLO', 8),
(362, 'EL DONCELLO', 8),
(363, 'EL PAUJIL', 8),
(364, 'FLORENCIA', 8),
(365, 'LA MONTAÑITA', 8),
(366, 'MILÁN', 8),
(367, 'MORELIA', 8),
(368, 'PUERTO RICO', 8),
(369, 'SAN VICENTE DEL CAGUAN', 8),
(370, 'SAN JOSÉ DE FRAGUA', 8),
(371, 'SOLANO', 8),
(372, 'SOLITA', 8),
(373, 'VALPARAÍSO', 8),
(374, 'AGUAZUL', 9),
(375, 'CHAMEZA', 9),
(376, 'HATO COROZAL', 9),
(377, 'LA SALINA', 9),
(378, 'MANÍ', 9),
(379, 'MONTERREY', 9),
(380, 'NUNCHIA', 9),
(381, 'OROCUE', 9),
(382, 'PAZ DE ARIPORO', 9),
(383, 'PORE', 9),
(384, 'RECETOR', 9),
(385, 'SABANA LARGA', 9),
(386, 'SACAMA', 9),
(387, 'SAN LUIS DE PALENQUE', 9),
(388, 'TAMARA', 9),
(389, 'TAURAMENA', 9),
(390, 'TRINIDAD', 9),
(391, 'VILLANUEVA', 9),
(392, 'YOPAL', 9),
(393, 'ALMAGUER', 10),
(394, 'ARGELIA', 10),
(395, 'BALBOA', 10),
(396, 'BOLÍVAR', 10),
(397, 'BUENOS AIRES', 10),
(398, 'CAJIBIO', 10),
(399, 'CALDONO', 10),
(400, 'CALOTO', 10),
(401, 'CORINTO', 10),
(402, 'EL TAMBO', 10),
(403, 'FLORENCIA', 10),
(404, 'GUAPI', 10),
(405, 'INZA', 10),
(406, 'JAMBALÓ', 10),
(407, 'LA SIERRA', 10),
(408, 'LA VEGA', 10),
(409, 'LÓPEZ', 10),
(410, 'MERCADERES', 10),
(411, 'MIRANDA', 10),
(412, 'MORALES', 10),
(413, 'PADILLA', 10),
(414, 'PÁEZ', 10),
(415, 'PATIA (EL BORDO)', 10),
(416, 'PIAMONTE', 10),
(417, 'PIENDAMO', 10),
(418, 'POPAYÁN', 10),
(419, 'PUERTO TEJADA', 10),
(420, 'PURACE', 10),
(421, 'ROSAS', 10),
(422, 'SAN SEBASTIÁN', 10),
(423, 'SANTA ROSA', 10),
(424, 'SANTANDER DE QUILICHAO', 10),
(425, 'SILVIA', 10),
(426, 'SOTARA', 10),
(427, 'SUÁREZ', 10),
(428, 'SUCRE', 10),
(429, 'TIMBÍO', 10),
(430, 'TIMBIQUÍ', 10),
(431, 'TORIBIO', 10),
(432, 'TOTORO', 10),
(433, 'VILLA RICA', 10),
(434, 'AGUACHICA', 11),
(435, 'AGUSTÍN CODAZZI', 11),
(436, 'ASTREA', 11),
(437, 'BECERRIL', 11),
(438, 'BOSCONIA', 11),
(439, 'CHIMICHAGUA', 11),
(440, 'CHIRIGUANÁ', 11),
(441, 'CURUMANÍ', 11),
(442, 'EL COPEY', 11),
(443, 'EL PASO', 11),
(444, 'GAMARRA', 11),
(445, 'GONZÁLEZ', 11),
(446, 'LA GLORIA', 11),
(447, 'LA JAGUA IBIRICO', 11),
(448, 'MANAURE BALCÓN DEL CESAR', 11),
(449, 'PAILITAS', 11),
(450, 'PELAYA', 11),
(451, 'PUEBLO BELLO', 11),
(452, 'RÍO DE ORO', 11),
(453, 'ROBLES (LA PAZ)', 11),
(454, 'SAN ALBERTO', 11),
(455, 'SAN DIEGO', 11),
(456, 'SAN MARTÍN', 11),
(457, 'TAMALAMEQUE', 11),
(458, 'VALLEDUPAR', 11),
(459, 'ACANDI', 12),
(460, 'ALTO BAUDO (PIE DE PATO)', 12),
(461, 'ATRATO', 12),
(462, 'BAGADO', 12),
(463, 'BAHIA SOLANO (MUTIS)', 12),
(464, 'BAJO BAUDO (PIZARRO)', 12),
(465, 'BOJAYA (BELLAVISTA)', 12),
(466, 'CANTON DE SAN PABLO', 12),
(467, 'CARMEN DEL DARIEN', 12),
(468, 'CERTEGUI', 12),
(469, 'CONDOTO', 12),
(470, 'EL CARMEN', 12),
(471, 'ISTMINA', 12),
(472, 'JURADO', 12),
(473, 'LITORAL DEL SAN JUAN', 12),
(474, 'LLORO', 12),
(475, 'MEDIO ATRATO', 12),
(476, 'MEDIO BAUDO (BOCA DE PEPE)', 12),
(477, 'MEDIO SAN JUAN', 12),
(478, 'NOVITA', 12),
(479, 'NUQUI', 12),
(480, 'QUIBDO', 12),
(481, 'RIO IRO', 12),
(482, 'RIO QUITO', 12),
(483, 'RIOSUCIO', 12),
(484, 'SAN JOSE DEL PALMAR', 12),
(485, 'SIPI', 12),
(486, 'TADO', 12),
(487, 'UNGUIA', 12),
(488, 'UNIÓN PANAMERICANA', 12),
(489, 'AYAPEL', 13),
(490, 'BUENAVISTA', 13),
(491, 'CANALETE', 13),
(492, 'CERETÉ', 13),
(493, 'CHIMA', 13),
(494, 'CHINÚ', 13),
(495, 'CIENAGA DE ORO', 13),
(496, 'COTORRA', 13),
(497, 'LA APARTADA', 13),
(498, 'LORICA', 13),
(499, 'LOS CÓRDOBAS', 13),
(500, 'MOMIL', 13),
(501, 'MONTELÍBANO', 13),
(502, 'MONTERÍA', 13),
(503, 'MOÑITOS', 13),
(504, 'PLANETA RICA', 13),
(505, 'PUEBLO NUEVO', 13),
(506, 'PUERTO ESCONDIDO', 13),
(507, 'PUERTO LIBERTADOR', 13),
(508, 'PURÍSIMA', 13),
(509, 'SAHAGÚN', 13),
(510, 'SAN ANDRÉS SOTAVENTO', 13),
(511, 'SAN ANTERO', 13),
(512, 'SAN BERNARDO VIENTO', 13),
(513, 'SAN CARLOS', 13),
(514, 'SAN PELAYO', 13),
(515, 'TIERRALTA', 13),
(516, 'VALENCIA', 13),
(517, 'AGUA DE DIOS', 14),
(518, 'ALBAN', 14),
(519, 'ANAPOIMA', 14),
(520, 'ANOLAIMA', 14),
(521, 'ARBELAEZ', 14),
(522, 'BELTRÁN', 14),
(523, 'BITUIMA', 14),
(524, 'BOGOTÁ DC', 14),
(525, 'BOJACÁ', 14),
(526, 'CABRERA', 14),
(527, 'CACHIPAY', 14),
(528, 'CAJICÁ', 14),
(529, 'CAPARRAPÍ', 14),
(530, 'CAQUEZA', 14),
(531, 'CARMEN DE CARUPA', 14),
(532, 'CHAGUANÍ', 14),
(533, 'CHIA', 14),
(534, 'CHIPAQUE', 14),
(535, 'CHOACHÍ', 14),
(536, 'CHOCONTÁ', 14),
(537, 'COGUA', 14),
(538, 'COTA', 14),
(539, 'CUCUNUBÁ', 14),
(540, 'EL COLEGIO', 14),
(541, 'EL PEÑÓN', 14),
(542, 'EL ROSAL1', 14),
(543, 'FACATATIVA', 14),
(544, 'FÓMEQUE', 14),
(545, 'FOSCA', 14),
(546, 'FUNZA', 14),
(547, 'FÚQUENE', 14),
(548, 'FUSAGASUGA', 14),
(549, 'GACHALÁ', 14),
(550, 'GACHANCIPÁ', 14),
(551, 'GACHETA', 14),
(552, 'GAMA', 14),
(553, 'GIRARDOT', 14),
(554, 'GRANADA2', 14),
(555, 'GUACHETÁ', 14),
(556, 'GUADUAS', 14),
(557, 'GUASCA', 14),
(558, 'GUATAQUÍ', 14),
(559, 'GUATAVITA', 14),
(560, 'GUAYABAL DE SIQUIMA', 14),
(561, 'GUAYABETAL', 14),
(562, 'GUTIÉRREZ', 14),
(563, 'JERUSALÉN', 14),
(564, 'JUNÍN', 14),
(565, 'LA CALERA', 14),
(566, 'LA MESA', 14),
(567, 'LA PALMA', 14),
(568, 'LA PEÑA', 14),
(569, 'LA VEGA', 14),
(570, 'LENGUAZAQUE', 14),
(571, 'MACHETÁ', 14),
(572, 'MADRID', 14),
(573, 'MANTA', 14),
(574, 'MEDINA', 14),
(575, 'MOSQUERA', 14),
(576, 'NARIÑO', 14),
(577, 'NEMOCÓN', 14),
(578, 'NILO', 14),
(579, 'NIMAIMA', 14),
(580, 'NOCAIMA', 14),
(581, 'OSPINA PÉREZ', 14),
(582, 'PACHO', 14),
(583, 'PAIME', 14),
(584, 'PANDI', 14),
(585, 'PARATEBUENO', 14),
(586, 'PASCA', 14),
(587, 'PUERTO SALGAR', 14),
(588, 'PULÍ', 14),
(589, 'QUEBRADANEGRA', 14),
(590, 'QUETAME', 14),
(591, 'QUIPILE', 14),
(592, 'RAFAEL REYES', 14),
(593, 'RICAURTE', 14),
(594, 'SAN ANTONIO DEL TEQUENDAMA', 14),
(595, 'SAN BERNARDO', 14),
(596, 'SAN CAYETANO', 14),
(597, 'SAN FRANCISCO', 14),
(598, 'SAN JUAN DE RIOSECO', 14),
(599, 'SASAIMA', 14),
(600, 'SESQUILÉ', 14),
(601, 'SIBATÉ', 14),
(602, 'SILVANIA', 14),
(603, 'SIMIJACA', 14),
(604, 'SOACHA', 14),
(605, 'SOPO', 14),
(606, 'SUBACHOQUE', 14),
(607, 'SUESCA', 14),
(608, 'SUPATÁ', 14),
(609, 'SUSA', 14),
(610, 'SUTATAUSA', 14),
(611, 'TABIO', 14),
(612, 'TAUSA', 14),
(613, 'TENA', 14),
(614, 'TENJO', 14),
(615, 'TIBACUY', 14),
(616, 'TIBIRITA', 14),
(617, 'TOCAIMA', 14),
(618, 'TOCANCIPÁ', 14),
(619, 'TOPAIPÍ', 14),
(620, 'UBALÁ', 14),
(621, 'UBAQUE', 14),
(622, 'UBATÉ', 14),
(623, 'UNE', 14),
(624, 'UTICA', 14),
(625, 'VERGARA', 14),
(626, 'VIANI', 14),
(627, 'VILLA GOMEZ', 14),
(628, 'VILLA PINZÓN', 14),
(629, 'VILLETA', 14),
(630, 'VIOTA', 14),
(631, 'YACOPÍ', 14),
(632, 'ZIPACÓN', 14),
(633, 'ZIPAQUIRÁ', 14),
(634, 'BARRANCO MINAS', 15),
(635, 'CACAHUAL', 15),
(636, 'INÍRIDA', 15),
(637, 'LA GUADALUPE', 15),
(638, 'MAPIRIPANA', 15),
(639, 'MORICHAL', 15),
(640, 'PANA PANA', 15),
(641, 'PUERTO COLOMBIA', 15),
(642, 'SAN FELIPE', 15),
(643, 'CALAMAR', 16),
(644, 'EL RETORNO', 16),
(645, 'MIRAFLOREZ', 16),
(646, 'SAN JOSÉ DEL GUAVIARE', 16),
(647, 'ACEVEDO', 17),
(648, 'AGRADO', 17),
(649, 'AIPE', 17),
(650, 'ALGECIRAS', 17),
(651, 'ALTAMIRA', 17),
(652, 'BARAYA', 17),
(653, 'CAMPO ALEGRE', 17),
(654, 'COLOMBIA', 17),
(655, 'ELIAS', 17),
(656, 'GARZÓN', 17),
(657, 'GIGANTE', 17),
(658, 'GUADALUPE', 17),
(659, 'HOBO', 17),
(660, 'IQUIRA', 17),
(661, 'ISNOS', 17),
(662, 'LA ARGENTINA', 17),
(663, 'LA PLATA', 17),
(664, 'NATAGA', 17),
(665, 'NEIVA', 17),
(666, 'OPORAPA', 17),
(667, 'PAICOL', 17),
(668, 'PALERMO', 17),
(669, 'PALESTINA', 17),
(670, 'PITAL', 17),
(671, 'PITALITO', 17),
(672, 'RIVERA', 17),
(673, 'SALADO BLANCO', 17),
(674, 'SAN AGUSTÍN', 17),
(675, 'SANTA MARIA', 17),
(676, 'SUAZA', 17),
(677, 'TARQUI', 17),
(678, 'TELLO', 17),
(679, 'TERUEL', 17),
(680, 'TESALIA', 17),
(681, 'TIMANA', 17),
(682, 'VILLAVIEJA', 17),
(683, 'YAGUARA', 17),
(684, 'ALBANIA', 18),
(685, 'BARRANCAS', 18),
(686, 'DIBULLA', 18),
(687, 'DISTRACCIÓN', 18),
(688, 'EL MOLINO', 18),
(689, 'FONSECA', 18),
(690, 'HATO NUEVO', 18),
(691, 'LA JAGUA DEL PILAR', 18),
(692, 'MAICAO', 18),
(693, 'MANAURE', 18),
(694, 'RIOHACHA', 18),
(695, 'SAN JUAN DEL CESAR', 18),
(696, 'URIBIA', 18),
(697, 'URUMITA', 18),
(698, 'VILLANUEVA', 18),
(699, 'ALGARROBO', 19),
(700, 'ARACATACA', 19),
(701, 'ARIGUANI', 19),
(702, 'CERRO SAN ANTONIO', 19),
(703, 'CHIVOLO', 19),
(704, 'CIENAGA', 19),
(705, 'CONCORDIA', 19),
(706, 'EL BANCO', 19),
(707, 'EL PIÑON', 19),
(708, 'EL RETEN', 19),
(709, 'FUNDACION', 19),
(710, 'GUAMAL', 19),
(711, 'NUEVA GRANADA', 19),
(712, 'PEDRAZA', 19),
(713, 'PIJIÑO DEL CARMEN', 19),
(714, 'PIVIJAY', 19),
(715, 'PLATO', 19),
(716, 'PUEBLO VIEJO', 19),
(717, 'REMOLINO', 19),
(718, 'SABANAS DE SAN ANGEL', 19),
(719, 'SALAMINA', 19),
(720, 'SAN SEBASTIAN DE BUENAVISTA', 19),
(721, 'SAN ZENON', 19),
(722, 'SANTA ANA', 19),
(723, 'SANTA BARBARA DE PINTO', 19),
(724, 'SANTA MARTA', 19),
(725, 'SITIONUEVO', 19),
(726, 'TENERIFE', 19),
(727, 'ZAPAYAN', 19),
(728, 'ZONA BANANERA', 19),
(729, 'ACACIAS', 20),
(730, 'BARRANCA DE UPIA', 20),
(731, 'CABUYARO', 20),
(732, 'CASTILLA LA NUEVA', 20),
(733, 'CUBARRAL', 20),
(734, 'CUMARAL', 20),
(735, 'EL CALVARIO', 20),
(736, 'EL CASTILLO', 20),
(737, 'EL DORADO', 20),
(738, 'FUENTE DE ORO', 20),
(739, 'GRANADA', 20),
(740, 'GUAMAL', 20),
(741, 'LA MACARENA', 20),
(742, 'LA URIBE', 20),
(743, 'LEJANÍAS', 20),
(744, 'MAPIRIPÁN', 20),
(745, 'MESETAS', 20),
(746, 'PUERTO CONCORDIA', 20),
(747, 'PUERTO GAITÁN', 20),
(748, 'PUERTO LLERAS', 20),
(749, 'PUERTO LÓPEZ', 20),
(750, 'PUERTO RICO', 20),
(751, 'RESTREPO', 20),
(752, 'SAN JUAN DE ARAMA', 20),
(753, 'SAN CARLOS GUAROA', 20),
(754, 'SAN JUANITO', 20),
(755, 'SAN MARTÍN', 20),
(756, 'VILLAVICENCIO', 20),
(757, 'VISTA HERMOSA', 20),
(758, 'ALBAN', 21),
(759, 'ALDAÑA', 21),
(760, 'ANCUYA', 21),
(761, 'ARBOLEDA', 21),
(762, 'BARBACOAS', 21),
(763, 'BELEN', 21),
(764, 'BUESACO', 21),
(765, 'CHACHAGUI', 21),
(766, 'COLON (GENOVA)', 21),
(767, 'CONSACA', 21),
(768, 'CONTADERO', 21),
(769, 'CORDOBA', 21),
(770, 'CUASPUD', 21),
(771, 'CUMBAL', 21),
(772, 'CUMBITARA', 21),
(773, 'EL CHARCO', 21),
(774, 'EL PEÑOL', 21),
(775, 'EL ROSARIO', 21),
(776, 'EL TABLÓN', 21),
(777, 'EL TAMBO', 21),
(778, 'FUNES', 21),
(779, 'GUACHUCAL', 21),
(780, 'GUAITARILLA', 21),
(781, 'GUALMATAN', 21),
(782, 'ILES', 21),
(783, 'IMUES', 21),
(784, 'IPIALES', 21),
(785, 'LA CRUZ', 21),
(786, 'LA FLORIDA', 21),
(787, 'LA LLANADA', 21),
(788, 'LA TOLA', 21),
(789, 'LA UNION', 21),
(790, 'LEIVA', 21),
(791, 'LINARES', 21),
(792, 'LOS ANDES', 21),
(793, 'MAGUI', 21),
(794, 'MALLAMA', 21),
(795, 'MOSQUEZA', 21),
(796, 'NARIÑO', 21),
(797, 'OLAYA HERRERA', 21),
(798, 'OSPINA', 21),
(799, 'PASTO', 21),
(800, 'PIZARRO', 21),
(801, 'POLICARPA', 21),
(802, 'POTOSI', 21),
(803, 'PROVIDENCIA', 21),
(804, 'PUERRES', 21),
(805, 'PUPIALES', 21),
(806, 'RICAURTE', 21),
(807, 'ROBERTO PAYAN', 21),
(808, 'SAMANIEGO', 21),
(809, 'SAN BERNARDO', 21),
(810, 'SAN LORENZO', 21),
(811, 'SAN PABLO', 21),
(812, 'SAN PEDRO DE CARTAGO', 21),
(813, 'SANDONA', 21),
(814, 'SANTA BARBARA', 21),
(815, 'SANTACRUZ', 21),
(816, 'SAPUYES', 21),
(817, 'TAMINANGO', 21),
(818, 'TANGUA', 21),
(819, 'TUMACO', 21),
(820, 'TUQUERRES', 21),
(821, 'YACUANQUER', 21),
(822, 'ABREGO', 22),
(823, 'ARBOLEDAS', 22),
(824, 'BOCHALEMA', 22),
(825, 'BUCARASICA', 22),
(826, 'CÁCHIRA', 22),
(827, 'CÁCOTA', 22),
(828, 'CHINÁCOTA', 22),
(829, 'CHITAGÁ', 22),
(830, 'CONVENCIÓN', 22),
(831, 'CÚCUTA', 22),
(832, 'CUCUTILLA', 22),
(833, 'DURANIA', 22),
(834, 'EL CARMEN', 22),
(835, 'EL TARRA', 22),
(836, 'EL ZULIA', 22),
(837, 'GRAMALOTE', 22),
(838, 'HACARI', 22),
(839, 'HERRÁN', 22),
(840, 'LA ESPERANZA', 22),
(841, 'LA PLAYA', 22),
(842, 'LABATECA', 22),
(843, 'LOS PATIOS', 22),
(844, 'LOURDES', 22),
(845, 'MUTISCUA', 22),
(846, 'OCAÑA', 22),
(847, 'PAMPLONA', 22),
(848, 'PAMPLONITA', 22),
(849, 'PUERTO SANTANDER', 22),
(850, 'RAGONVALIA', 22),
(851, 'SALAZAR', 22),
(852, 'SAN CALIXTO', 22),
(853, 'SAN CAYETANO', 22),
(854, 'SANTIAGO', 22),
(855, 'SARDINATA', 22),
(856, 'SILOS', 22),
(857, 'TEORAMA', 22),
(858, 'TIBÚ', 22),
(859, 'TOLEDO', 22),
(860, 'VILLA CARO', 22),
(861, 'VILLA DEL ROSARIO', 22),
(862, 'COLÓN', 23),
(863, 'MOCOA', 23),
(864, 'ORITO', 23),
(865, 'PUERTO ASÍS', 23),
(866, 'PUERTO CAYCEDO', 23),
(867, 'PUERTO GUZMÁN', 23),
(868, 'PUERTO LEGUÍZAMO', 23),
(869, 'SAN FRANCISCO', 23),
(870, 'SAN MIGUEL', 23),
(871, 'SANTIAGO', 23),
(872, 'SIBUNDOY', 23),
(873, 'VALLE DEL GUAMUEZ', 23),
(874, 'VILLAGARZÓN', 23),
(875, 'ARMENIA', 24),
(876, 'BUENAVISTA', 24),
(877, 'CALARCÁ', 24),
(878, 'CIRCASIA', 24),
(879, 'CÓRDOBA', 24),
(880, 'FILANDIA', 24),
(881, 'GÉNOVA', 24),
(882, 'LA TEBAIDA', 24),
(883, 'MONTENEGRO', 24),
(884, 'PIJAO', 24),
(885, 'QUIMBAYA', 24),
(886, 'SALENTO', 24),
(887, 'APIA', 25),
(888, 'BALBOA', 25),
(889, 'BELÉN DE UMBRÍA', 25),
(890, 'DOS QUEBRADAS', 25),
(891, 'GUATICA', 25),
(892, 'LA CELIA', 25),
(893, 'LA VIRGINIA', 25),
(894, 'MARSELLA', 25),
(895, 'MISTRATO', 25),
(896, 'PEREIRA', 25),
(897, 'PUEBLO RICO', 25),
(898, 'QUINCHÍA', 25),
(899, 'SANTA ROSA DE CABAL', 25),
(900, 'SANTUARIO', 25),
(901, 'PROVIDENCIA', 26),
(902, 'SAN ANDRES', 26),
(903, 'SANTA CATALINA', 26),
(904, 'AGUADA', 27),
(905, 'ALBANIA', 27),
(906, 'ARATOCA', 27),
(907, 'BARBOSA', 27),
(908, 'BARICHARA', 27),
(909, 'BARRANCABERMEJA', 27),
(910, 'BETULIA', 27),
(911, 'BOLÍVAR', 27),
(912, 'BUCARAMANGA', 27),
(913, 'CABRERA', 27),
(914, 'CALIFORNIA', 27),
(915, 'CAPITANEJO', 27),
(916, 'CARCASI', 27),
(917, 'CEPITA', 27),
(918, 'CERRITO', 27),
(919, 'CHARALÁ', 27),
(920, 'CHARTA', 27),
(921, 'CHIMA', 27),
(922, 'CHIPATÁ', 27),
(923, 'CIMITARRA', 27),
(924, 'CONCEPCIÓN', 27),
(925, 'CONFINES', 27),
(926, 'CONTRATACIÓN', 27),
(927, 'COROMORO', 27),
(928, 'CURITÍ', 27),
(929, 'EL CARMEN', 27),
(930, 'EL GUACAMAYO', 27),
(931, 'EL PEÑÓN', 27),
(932, 'EL PLAYÓN', 27),
(933, 'ENCINO', 27),
(934, 'ENCISO', 27),
(935, 'FLORIÁN', 27),
(936, 'FLORIDABLANCA', 27),
(937, 'GALÁN', 27),
(938, 'GAMBITA', 27),
(939, 'GIRÓN', 27),
(940, 'GUACA', 27),
(941, 'GUADALUPE', 27),
(942, 'GUAPOTA', 27),
(943, 'GUAVATÁ', 27),
(944, 'GUEPSA', 27),
(945, 'HATO', 27),
(946, 'JESÚS MARIA', 27),
(947, 'JORDÁN', 27),
(948, 'LA BELLEZA', 27),
(949, 'LA PAZ', 27),
(950, 'LANDAZURI', 27),
(951, 'LEBRIJA', 27),
(952, 'LOS SANTOS', 27),
(953, 'MACARAVITA', 27),
(954, 'MÁLAGA', 27),
(955, 'MATANZA', 27),
(956, 'MOGOTES', 27),
(957, 'MOLAGAVITA', 27),
(958, 'OCAMONTE', 27),
(959, 'OIBA', 27),
(960, 'ONZAGA', 27),
(961, 'PALMAR', 27),
(962, 'PALMAS DEL SOCORRO', 27),
(963, 'PÁRAMO', 27),
(964, 'PIEDECUESTA', 27),
(965, 'PINCHOTE', 27),
(966, 'PUENTE NACIONAL', 27),
(967, 'PUERTO PARRA', 27),
(968, 'PUERTO WILCHES', 27),
(969, 'RIONEGRO', 27),
(970, 'SABANA DE TORRES', 27),
(971, 'SAN ANDRÉS', 27),
(972, 'SAN BENITO', 27),
(973, 'SAN GIL', 27),
(974, 'SAN JOAQUÍN', 27),
(975, 'SAN JOSÉ DE MIRANDA', 27),
(976, 'SAN MIGUEL', 27),
(977, 'SAN VICENTE DE CHUCURÍ', 27),
(978, 'SANTA BÁRBARA', 27),
(979, 'SANTA HELENA', 27),
(980, 'SIMACOTA', 27),
(981, 'SOCORRO', 27),
(982, 'SUAITA', 27),
(983, 'SUCRE', 27),
(984, 'SURATA', 27),
(985, 'TONA', 27),
(986, 'VALLE SAN JOSÉ', 27),
(987, 'VÉLEZ', 27),
(988, 'VETAS', 27),
(989, 'VILLANUEVA', 27),
(990, 'ZAPATOCA', 27),
(991, 'BUENAVISTA', 28),
(992, 'CAIMITO', 28),
(993, 'CHALÁN', 28),
(994, 'COLOSO', 28),
(995, 'COROZAL', 28),
(996, 'EL ROBLE', 28),
(997, 'GALERAS', 28),
(998, 'GUARANDA', 28),
(999, 'LA UNIÓN', 28),
(1000, 'LOS PALMITOS', 28),
(1001, 'MAJAGUAL', 28),
(1002, 'MORROA', 28),
(1003, 'OVEJAS', 28),
(1004, 'PALMITO', 28),
(1005, 'SAMPUES', 28),
(1006, 'SAN BENITO ABAD', 28),
(1007, 'SAN JUAN DE BETULIA', 28),
(1008, 'SAN MARCOS', 28),
(1009, 'SAN ONOFRE', 28),
(1010, 'SAN PEDRO', 28),
(1011, 'SINCÉ', 28),
(1012, 'SINCELEJO', 28),
(1013, 'SUCRE', 28),
(1014, 'TOLÚ', 28),
(1015, 'TOLUVIEJO', 28),
(1016, 'ALPUJARRA', 29),
(1017, 'ALVARADO', 29),
(1018, 'AMBALEMA', 29),
(1019, 'ANZOATEGUI', 29),
(1020, 'ARMERO (GUAYABAL)', 29),
(1021, 'ATACO', 29),
(1022, 'CAJAMARCA', 29),
(1023, 'CARMEN DE APICALÁ', 29),
(1024, 'CASABIANCA', 29),
(1025, 'CHAPARRAL', 29),
(1026, 'COELLO', 29),
(1027, 'COYAIMA', 29),
(1028, 'CUNDAY', 29),
(1029, 'DOLORES', 29),
(1030, 'ESPINAL', 29),
(1031, 'FALÁN', 29),
(1032, 'FLANDES', 29),
(1033, 'FRESNO', 29),
(1034, 'GUAMO', 29),
(1035, 'HERVEO', 29),
(1036, 'HONDA', 29),
(1037, 'IBAGUÉ', 29),
(1038, 'ICONONZO', 29),
(1039, 'LÉRIDA', 29),
(1040, 'LÍBANO', 29),
(1041, 'MARIQUITA', 29),
(1042, 'MELGAR', 29),
(1043, 'MURILLO', 29),
(1044, 'NATAGAIMA', 29),
(1045, 'ORTEGA', 29),
(1046, 'PALOCABILDO', 29),
(1047, 'PIEDRAS PLANADAS', 29),
(1048, 'PRADO', 29),
(1049, 'PURIFICACIÓN', 29),
(1050, 'RIOBLANCO', 29),
(1051, 'RONCESVALLES', 29),
(1052, 'ROVIRA', 29),
(1053, 'SALDAÑA', 29),
(1054, 'SAN ANTONIO', 29),
(1055, 'SAN LUIS', 29),
(1056, 'SANTA ISABEL', 29),
(1057, 'SUÁREZ', 29),
(1058, 'VALLE DE SAN JUAN', 29),
(1059, 'VENADILLO', 29),
(1060, 'VILLAHERMOSA', 29),
(1061, 'VILLARRICA', 29),
(1062, 'ALCALÁ', 30),
(1063, 'ANDALUCÍA', 30),
(1064, 'ANSERMA NUEVO', 30),
(1065, 'ARGELIA', 30),
(1066, 'BOLÍVAR', 30),
(1067, 'BUENAVENTURA', 30),
(1068, 'BUGA', 30),
(1069, 'BUGALAGRANDE', 30),
(1070, 'CAICEDONIA', 30),
(1071, 'CALI', 30),
(1072, 'CALIMA (DARIEN)', 30),
(1073, 'CANDELARIA', 30),
(1074, 'CARTAGO', 30),
(1075, 'DAGUA', 30),
(1076, 'EL AGUILA', 30),
(1077, 'EL CAIRO', 30),
(1078, 'EL CERRITO', 30),
(1079, 'EL DOVIO', 30),
(1080, 'FLORIDA', 30),
(1081, 'GINEBRA GUACARI', 30),
(1082, 'JAMUNDÍ', 30),
(1083, 'LA CUMBRE', 30),
(1084, 'LA UNIÓN', 30),
(1085, 'LA VICTORIA', 30),
(1086, 'OBANDO', 30),
(1087, 'PALMIRA', 30),
(1088, 'PRADERA', 30),
(1089, 'RESTREPO', 30),
(1090, 'RIO FRÍO', 30),
(1091, 'ROLDANILLO', 30),
(1092, 'SAN PEDRO', 30),
(1093, 'SEVILLA', 30),
(1094, 'TORO', 30),
(1095, 'TRUJILLO', 30),
(1096, 'TULÚA', 30),
(1097, 'ULLOA', 30),
(1098, 'VERSALLES', 30),
(1099, 'VIJES', 30),
(1100, 'YOTOCO', 30),
(1101, 'YUMBO', 30),
(1102, 'ZARZAL', 30),
(1103, 'CARURÚ', 31),
(1104, 'MITÚ', 31),
(1105, 'PACOA', 31),
(1106, 'PAPUNAUA', 31),
(1107, 'TARAIRA', 31),
(1108, 'YAVARATÉ', 31),
(1109, 'CUMARIBO', 32),
(1110, 'LA PRIMAVERA', 32),
(1111, 'PUERTO CARREÑO', 32),
(1112, 'SANTA ROSALIA', 32);
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `departamento`
--
ALTER TABLE `departamento`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `municipio`
--
ALTER TABLE `municipio`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `departamento`
--
ALTER TABLE `departamento`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=33;
--
-- AUTO_INCREMENT de la tabla `municipio`
--
ALTER TABLE `municipio`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1113;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
DROP DATABASE IF EXISTS bamazon1_DB;
CREATE DATABASE bamazon1_DB;
USE bamazon1DB;
CREATE TABLE products (
id INT(10) NOT NULL AUTO_INCREMENT,
produrt_name VARCHAR(45) NULL,
product_name VARCHAR(45) NULL,
price DECIMAL(5,2) NULL,
stock_quantity INT (10) NULL,
PRIMARY KEY (id)
);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("Echo Spot - White","Electronics", 129.99, 20);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ( "4K LED TV", "Electronics", 299.99, 5);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ( "GoPro", "Electronics", 149.99, 50);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ( "Citrus Juicer", "Appliances", 22.49, 125);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ( "12 Cup CoffeeMaker", "Appliances", 34.99, 200);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ( "2-Slice Toaster", "Appliances", 18.99, 50);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ( "Shag Rug", "Home", 35.99, 200);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ( "Alarm Clock", "Home", 15.99, 350);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ( "Queen Mattress", "Bed & Bath" , 649.99, 35);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ( "Comforter", "Bed & Bath", 79.99, 75);
|
use employees;
desc employees;
-- select 연습
select * from departments;
select dept_no, dept_name from departments;
-- alias (as 별칭)
-- ex) employees 테이블에서 직원의 이름, 성별, 입사일을 출력
select first_name as 이름, gender as 성별, hire_date as 입사일 from employees;
-- ex) employees 테이블에서 직원의 이름, 성별, 입사일을 출력
-- concat() - 문자열을 합쳐줌
select concat(first_name,'',last_name) as 이름, gender as 성별, hire_date as 입사일 from employees;
-- ex) titles 테이블에서 모든 직급의 이름을 출력
-- distinct - 중복 제거
select title from titles limit 0,3;
select title from titles limit 3,3;
-- 계시판 5개씩 출력할때 limit (i-1)*5,5
select distinct title from titles;
-- ex)1991년 이전에 입사한 직원의 이름, 성별, 입사일을 출력
select * from employees;
select concat(first_name,'',last_name), gender, hire_date from employees where hire_date < '1991-01-01' order by hire_date desc;
-- ex)1989년 이전에 입사한 여직원
-- 논리 연산자
select first_name, gender, hire_date from employees where hire_date < '1989-01-01' and gender ='F';
-- ex)dept_emp 테이블에서 부서 번호가 d005나 d009에 속한 사원의 사번, 부서 번호
-- in 연산자
select * from dept_emp;
select emp_no, dept_no from dept_emp where dept_no = 'd005' or dept_no ='d009';
select emp_no, dept_no from dept_emp where dept_no in('d005','d009');
-- 서브쿼리 select, from, where 절에 올 수 있다.
select emp_no, dept_no from dept_emp where dept_no in(select 'd005');
-- ex)1989년에 입사한 직원의 이름, 입사일을 출력하시오
-- like 검색
select first_name, hire_date from employees where hire_date like '1989%';
-- ex) 남자 직원의 전체 이름, 성별, 입사일을 입사일 순(선입순)으로 출력하라
select * from employees;
select concat(first_name,'',last_name), gender, hire_date from employees where gender='M' order by hire_date asc;
-- ex) 직원들의 사번, 월급을 사번,월급,이름 순으로 출력
select * from salaries;
select * from employees;
select * from salaries join employees where salaries.emp_no=employees.emp_no;
select salary, first_name from salaries join employees where salaries.emp_no=employees.emp_no order by salary asc;
select emp_no,salary from salaries order by emp_no asc,salary desc;
-- 함수 : 문자열 함수
-- upper() - 모든 문자열 대문자로 만들어줌
select upper('buSan'), upper('busan'), upper('Douzone');
select upper(first_name) from employees;
-- lower() - 모든 문자열 소문자로 만들어줌
select lower('buSan'), lower('busan'), lower('Douzone');
-- substring(문자열, index, length)
-- ll
select substring('hello world',3,2);
-- ex) 1989년에 입사한 사원들의 이름, 입사일 출력
select first_name, hire_date from employees where hire_date=substring(hire_date, 1, 4);
select * from employees;
-- lpad(오른쪽 정렬), rpad
-- 10자리 공간을 생성하고 빈공간을 -로 채운다analyze
select lpad('1234', 10, '-');
select rpad('1234', 10, '-');
-- ex) 직원들의 월급을 오른쪽 정렬로 빈공간을 *
select lpad(salary,10,'*') from salaries;
-- trim(공백 제거) ltrim = 왼쪽 공백 없애줌, rtrim = 오른쪽 공백 없애줌
select concat('---',ltrim(' hello '),'---');
select concat('---',rtrim(' hello '),'---');
select concat('---',ltrim(' hello '),'---'),
concat('---',rtrim(' hello '),'---'),
concat('---',trim(both 'X' from 'xxhelloxxx'),'---');
-- abs
select abs(-1), abs(1);
-- mod
select mod(10,3);
-- floor
select floor(3.14);
-- ceil
select ceil(3.14);
select ceiling(3.14);
-- round : 반올림
-- round(x) : x에 가장 근접한 정수
select round(1.598);
-- round(x,d) : x값 중에 소수점d자리에 가장 근접한 실수
select round(1.598, 1);
-- pow(x,y) : x의 y승
select pow(2,10), pow(10,2);
-- sign(x)
select sign(20), sign(-100), sign(0);
-- greatest(x,y, .......), least(x,y, ........)
select greatest(10,40,20,30), least(10,40,20,30);
select greatest('b','A','C'), least('hello','HELLO','HelloH');
-- 함수 : 날짜 함수
-- CURDATE(), CURRENT_DATE
select curdate(), current_date();
-- 시간
-- CURTIME(), CURRENT_TIME
select curtime(),current_time();
-- now(), sysdate()
select now();
select sysdate();
select now(), sysdate();
select now(),sleep(2),now();
select sysdate(),sleep(2),sysdate();
-- date_format(date, format)
select date_format(now(),'%Y년 %m월 %d일 %h시%i분%s초');
select date_format(now(),'%Y년 %c월 %d일 %h시%i분%s초');
-- period_diff : 두 날짜의 차이를 알려줌
-- YYMM, YYYYMM
-- ex) 근무 개월 수를 출력하시오
select first_name, period_diff(date_format(curdate(), '%Y%m'), date_format(hire_date,'%Y%m')) as 근속날짜 from employees order by 근속날짜 desc;
-- date_add(=adddate), date_sub(=subdate)
-- 날짜를 date에 type(day, month, year) 형식으로 더하거나 뺀다.
-- ex) 각 사원들의 근무 년수가 5년이 되는 날은 언제인가.
-- interval 5 year = 5년 / month = 5개월
select first_name, hire_date, date_add(hire_date, interval 5 month) from employees;
-- cast 데이터 타입 바꾸기 cast('바꿀거' as 타입)
select '1234'+10, cast('12345' as int) + 10;
select date_format(cast('2021-10-01' as date), '%Y-%m-%d');
select cast(1-2 as unsigned);
select casT(cast(1-2 as unsigned)as signed);
-- mysql, type
-- 문자 : varchar() < cahr < text < CLOB(Character Large OBject)
-- 정수 : signed(unsigned), int(integer), medium int, big int, int(11)
-- float, double
-- 날짜 : time, date, datetime
-- LOB : CLOB, BLOB
|
/* Создание просмотра водителей на стоянках с положительным балансом */
CREATE VIEW /*PERFIX*/S_DRIVER_POSITIVE_PARKS
AS
SELECT *
FROM /*PREFIX*/S_DRIVER_PARKS
WHERE (MIN_BALANCE IS NULL)
OR (ACTUAL_BALANCE>MIN_BALANCE)
--
/* Фиксация изменений */
COMMIT |
create or replace PACKAGE BODY PRUEBAS_PROFESORES AS
PROCEDURE inicializar AS
BEGIN
DELETE FROM profesores;
END inicializar;
PROCEDURE insertar (nombre_prueba VARCHAR2,W_OID_P NUMBER,w_oid_m NUMBER,salidaEsperada BOOLEAN) AS
salida BOOLEAN := true;
profesor profesores%ROWTYPE;
BEGIN
INSERT INTO profesores VALUES(W_OID_P,w_oid_m);
SELECT * INTO profesor FROM profesores WHERE OID_P=w_oid_p;
IF (profesor.oid_m<>w_oid_m) THEN
salida := false;
END IF;
COMMIT WORK;
DBMS_OUTPUT.put_line(nombre_prueba || ':' || ASSERT_EQUALS(salida,salidaEsperada));
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.put_line(nombre_prueba || ':' || ASSERT_EQUALS(false,salidaEsperada));
ROLLBACK;
END insertar;
PROCEDURE actualizar(nombre_prueba VARCHAR2,w_OID_P NUMBER, w_oid_m NUMBER,salidaEsperada BOOLEAN)
AS
salida BOOLEAN:=true;
profesor profesores%ROWTYPE;
BEGIN
UPDATE profesores SET oid_m=w_oid_m WHERE OID_P=W_OID_P;
SELECT * INTO profesor FROM profesores WHERE OID_P=W_OID_P;
IF (profesor.oid_m<>w_oid_m) THEN
salida:= false;
END IF;
COMMIT WORK;
DBMS_OUTPUT.put_line(nombre_prueba|| ':' || ASSERT_EQUALS(salida, salidaEsperada));
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.put_line(nombre_prueba|| ':' || ASSERT_EQUALS(false, salidaEsperada));
ROLLBACK;
END actualizar;
PROCEDURE eliminar(nombre_prueba VARCHAR2, w_OID_P NUMBER,salidaEsperada BOOLEAN)AS
salida BOOLEAN := true;
n_profesores INTEGER;
BEGIN
DELETE FROM profesores WHERE OID_P=W_OID_P;
SELECT COUNT (*) INTO n_profesores FROM profesores WHERE oid_p=w_oid_p;
IF(n_PROFESORES <>0) THEN
salida :=false;
END IF;
COMMIT WORK;
DBMS_OUTPUT.put_line(nombre_prueba || ':' || ASSERT_EQUALS(salida, salidaEsperada));
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.put_line(nombre_prueba || ':' || ASSERT_EQUALS(false, salidaEsperada));
ROLLBACK;
END eliminar;
END PRUEBAS_PROFESORES; |
/*
Navicat MySQL Data Transfer
Source Server : mysql
Source Server Version : 50514
Source Host : localhost:3306
Source Database : odontologia
Target Server Type : MYSQL
Target Server Version : 50514
File Encoding : 65001
Date: 2011-08-19 19:36:49
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `usuario`
-- ----------------------------
DROP TABLE IF EXISTS `usuario`;
CREATE TABLE `usuario` (
`usuario` varchar(10) NOT NULL DEFAULT '',
`clave` varchar(8) DEFAULT NULL,
`nombre` varchar(30) DEFAULT NULL,
PRIMARY KEY (`usuario`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of usuario
-- ----------------------------
INSERT INTO `usuario` VALUES ('user1', '1234', 'someone');
INSERT INTO `usuario` VALUES ('user2', '1234', 'other');
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.