text stringlengths 6 9.38M |
|---|
create table cart(id serial primary key,
buyer_id integer ,
created_at timestamp);
create table cart_item(id serial primary key,
product_id integer ,
cart_id integer,
created_at timestamp,
qty integer ,
constraint fk foreign key (cart_id) references cart(id));
create table invoice(id serial primary key,
buyer_id integer ,
buyer_name varchar(255),
prcs_date timestamp ,
created_at timestamp,
tot_price numeric);
create table invoice_detail(id serial primary key,
seller_id integer ,
invoice_id integer,
product_id integer,
product_name varchar(255),
seller_name varchar(255),
created_at timestamp,
price numeric,
qty integer,
constraint fk foreign key (invoice_id) references invoice(id)); |
-- user1 화면입니다.
SELECT * FROM tbl_dept;
SELECT * FROM tbl_dept WHERE d_name = '관광학';
-- 현재 학과테이블의 학과명중에 관광학 학과를 관광정보학으로 변경을 하려고 한다.
-- 1. 내가 변경하고자하는 조건에 맞는 데이터가 있는 확인
SELECT * FROM tbl_dept WHERE d_name = '관광학';
-- 2. SELECTION 한 결과가 1개의 레코드만 나타나고 있지만, d_name은 PK가 아니다.
-- 여기에서 보여주는 데이터는 리스트이다.
-- UPDATE tbl_dept SET d_name = '관광정보학' WHERE d_name = '관광학' 처럼
-- 명령을 수행하면 안된다.
-- 3. 조회된 결과에서 PK이 무엇인지를 파악해야 한다.
-- 4. PK를 조건으로 데이터를 UPDATE 수행해야 한다.
UPDATE tbl_dept SET d_name = '관광정보학' WHERE d_code = 'D001';
SELECT * FROM tbl_dept;
-- INSERT
INSERT INTO tbl_dept(d_code, d_name, d_prof) VALUES('D006', '무역학', '김선달');
/*
---------------------------- DELETE -----------------------------------------
DBMS의 스키마에 포함된 Table중에 여러 업무를 수행하는데 필요한 Table을
보통 Master Data Table이라고 한다.(학생정보, 학과정보)
Master Data는 초기에 INSERT가 수행된 후에 업무가 진행동안
가급적 데이터를 변경하거나, 삭제하는 일이 최소화 되어야 하는 데이터이다.
Master Data와 Relation을 하여 생성되는 여러데이터들의 무결을 위해서
Master Data는 변경을 최소화 하면서 유지 해야 한다.
DBMS의 스키마에 포함된 Table중에 수시로 데이터가 추가, 변경, 삭제가 필요한 Table을
보통 Work Data Table이라고 한다. (성적정보)
통계, 집계 등 보고서를 작성하는 기본 데이터가 된다.
통계, 집계 등 보고서를 작성한후 데이터를 검증하였을때 이상이 있으면
데이터를 수정, 삭제를 수행하여 정정하는 과정이 이루어진다.
Work Data는 Master Table과 Relation을 잘 연동하여 데이터를 INSERT 하는 단계부터
잘못된 데이터가 추가되는 것을 막아줄 필요가 있다.
이때 설정하는 조건중에 외래키 연관조건이 있다.
*/
SELECT * FROM tbl_score;
UPDATE tbl_score -- 변경할 테이블
SET sc_kor = 90 -- 변경할 대상 = 값
WHERE sc_num ='20015'; -- 조건(Update에서 WHERE는 선택사항이나, 실무에서는 필수사항으로 인식)
SELECT sc_kor FROM tbl_score WHERE sc_num = '20015';
UPDATE tbl_score SET sc_kor = 77, sc_eng = 77, sc_math = 77 WHERE sc_num = '20001';
SELECT * FROM tbl_score;
-- SQL문으로 CUD(INSERT, UPDATE, DELETE)를 수행하고 난 직후에는
-- TABLE의 변경된 데이터가 물리적(스토리지)에 반영(여기서는 COMMIT)이 아직 안된상태에서
-- ROLLBACK 명령을 잘못 수행하면, 정상적으로 변경(CUD) 필요한 데이터마저 변경이 취소되어 문제를 일으킬수 있다.
COMMIT;
UPDATE tbl_score
SET sc_kor = 100;
ROLLBACK;
SELECT * FROM tbl_score;
-- 20020 학번의 학생이 시험날 결석을 하여 시험응시를 하지 못했는데 성적이 입력되었다.
-- 이 학생의 성적데이터는 삭제되어야 한다.
-- 20020 학생이 정말 시험날 결석한 학생인지 확인하는 절차가 필요하다.
-- 20020 학생의 학생정보를 확인하고, 만약 이 학생의 성적정보가 등록되어 있다면
-- 삭제를 수행하자.
SELECT * FROM tbl_student WHERE st_num = '20020';
-- 성적정보가 모든 sc_xxx (null)로 나타나면 성적정보가 등록 X
-- X라면 성적정보를 삭제할 필요하지 않는다.
-- 성적정보가(sc_xxx) 한개라도 null이 아니라면 학생성적정보가 등록되었다고 판단하여 삭제해야 한다.
SELECT * FROM tbl_student ST
LEFT JOIN tbl_score SC
ON ST.st_num = SC.sc_num
WHERE ST.st_num = '20020';
-- sc_num 데이터에 없는 조건을 부여하면 DELETE를 수행하지 않을뿐 오류가 나거나 하지는 않는다.
DELETE FROM tbl_score WHERE sc_num = '20020';
ROLLBACK;
-- 성적데이터의 국어점수가 가장 높은 값과 가장 낮은값은 무엇인가?
SELECT MAX(sc_kor), MIN(Sc_kor) FROM tbl_score;
-- 이중 LEFT JOIN은 첫 LEFT JOIN 이후 두번째 LEFT_JOIN 부터는 기준 Table에 LEFT JOIN에 포함시키는 개념
-- FROM X1_Table(기준) LEFT JOIN X2_Table(기준 Table(X1)에 JOIN) 두번째 LEFT JOIN X3_Table은 X1_Table에 JOIN
--------------------------------------------------------------------------------
-- SUB QUERY
/*
두번이상 SELECT 수행해서 결과를 만들어야 하는 경우
첫번째 SELECT 결과를 두번째 SELECT에 주입하여
동시에 두번이상의 SELECT를 수행하는 방법
sub query는 JOIN으로 모두 구현이 가능하다.
하지만 간단한 동작을 요구할때는 sub query를 사용하는 것이 쉬운 방법이기도 하다.
또한 아로클 관련 정보들(구글링)중에 JOIN보다는 sub query를 사용한 예제들이
많아서 코딩에 다소 유리한면도 있다.
sub query를 사용하게 되면 SELECT 여러번 실행되기 떄문에 약간만 코딩이 변경이 되어도
상당히 느린 실행결과를 낳게된다.
*/
--------------------------------------------------------------------------------
-- WHERE 절에서 subQuery 사용하기
-- WHERE 처음에 칼럼명이 오고 (<=>) 오른쪽에 괄호를 포함한 SELEC 쿼리가 나와야 한다.
-- SUB QUERY로 작동되는 SELECT 문은 기본적으로 1개의 결과만 나와야 한다.
-- SUB QUERY의해 연산된 결과의 값을 기준으로 조건문을 부여하는 방식
-- SUB QUERY는 Method, 함수를 호출하는 것과 같이 sub query가 return 해주는 값을
-- 칼럼과 비교하여 최종 결과물을 낸다.
SELECT d_name, st_name, st_num, sc_kor FROM tbl_score
LEFT JOIN tbl_student ON sc_num = st_num
LEFT JOIN tbl_dept ON st_dept = d_code
WHERE sc_kor = (SELECT MAX(sc_kor) FROM tbl_score) OR
sc_kor = (SELECT MIN(sc_kor) FROM tbl_score);
SELECT MAX(sc_kor) FROM tbl_score ;
SELECT st_num, sc_num, st_name, sc_kor
FROM tbl_score
LEFT JOIN tbl_student ON st_num = sc_num
WHERE sc_kor = 99;
-- 오답
SELECT st_name, st_num, MAX(sc_kor) FROM tbl_student LEFT JOIN tbl_score ON st_num = sc_num GROUP BY st_name, st_num, sc_kor ORDER BY sc_kor DESC;
SELECT st_name, st_num, MAX(sc_kor) FROM tbl_student LEFT JOIN tbl_score ON st_num = sc_num GROUP BY st_name, st_num, sc_kor ORDER BY sc_kor ASC;
-- 국어 점수의 평균을 구하고 평균점수보다 높은 점수를 얻은 학생들의 리스트를 구하고 싶다.
SELECT AVG(sc_kor) FROM tbl_score;
SELECT sc_kor FROM tbl_score WHERE sc_kor >= ( SELECT AVG(sc_kor) FROM tbl_score);
-- 각 학생의 점수 평균을 구하고
-- 전체학생의 평균을 구하여
-- 각 학생의 평균점수가 전체학생의 평균점수보다 높은 리스트를 조회하시오
-- 학생 평균
SELECT sc_kor FROM tbl_score WHERE sc_kor >= ( SELECT AVG(sc_kor) FROM tbl_score);
-- 전체 평균
SELECT AVG((sc_kor+ sc_eng + sc_math + sc_music + sc_art) / 5) FROM tbl_score;
/*
쿼리 실행순서, 1. FROM 테이블의 정보(칼럼정보)를 가져오기
2. WHERE 절이 실행되어서 실제 가져올 데이터를 선별
3. GROUP BY이 실행되어 중복된 데이터를 묶어서 하나로 만든다.
4. SELECT에 나열된 칼럼에 값을 채워넣고,
5. SELECT에 정의된 수식을 연산, 결과를 보일준비
6. ODER BY는 모든 쿼리가 실행되고 가장 마지막에 연산 수행되어 정렬을 한다.
WHERE 절과 GROUP BY 절에서는 AS(Alias로 설정된 칼럼 이름을 사용할 수 없음)
ORDER BY 에서는 AS로 설정된 칼럼 이름을 사용할수 있다.
*/
SELECT sc_num, (sc_kor+ sc_eng + sc_math + sc_music + sc_art)/5
FROM tbl_score
WHERE ((sc_kor+ sc_eng + sc_math + sc_music + sc_art) / 5) >= (SELECT (AVG(sc_kor+ sc_eng + sc_math + sc_music + sc_art) / 5) FROM tbl_score);
-- 위의 QUERY를 활용하여 평균을 구하는 조건은 그대로 유지하고 학번이 20020 이전의 학생들만 추출하기
SELECT sc_num, (sc_kor+ sc_eng + sc_math + sc_music + sc_art)/5
FROM tbl_score
WHERE ((sc_kor+ sc_eng + sc_math + sc_music + sc_art) / 5) >= (SELECT (AVG(sc_kor+ sc_eng + sc_math + sc_music + sc_art) / 5) FROM tbl_score) AND sc_num < '20020';
-- 성적 테이블에서 학번의 문자열을 자르기 수행하여
-- 반 명칭만 추출하기
SELECT SUBSTR(sc_num,1,4) AS 반
FROM tbl_score
GROUP BY SUBSTR(sc_num,1,4)
ORDER BY 반;
-- 추출된 반 명칭이 '2006' 보다 작은 값을 갖는 반만 추출
-- HAVING : 성질이 WHERE와 매우 비슷하다.
-- 하늘이 GROUP BY로 묶이거나 통계함수로 생성값을 대상으로
-- WHERE 연산을 수행하는 키워드
-- 각반의 평균을 구하는 코드
SELECT SUBSTR(sc_num,1,4) AS 반
FROM tbl_score
GROUP BY SUBSTR(sc_num,1,4)
HAVING SUBSTR(sc_num,1,4) < '2006'
ORDER BY 반;
SELECT SUBSTR(sc_num,1,4) AS 반, ROUND(AVG(sc_kor + sc_eng + sc_math) / 3) -- 반평균
FROM tbl_score
GROUP BY SUBSTR(sc_num,1,4)
HAVING ROUND(AVG(sc_kor + sc_eng + sc_math) / 3) >= 80
ORDER BY 반;
-- 2000 - 20005까지는 A 그룹, 2006 - 2010까지는 B 그룹일때
-- A그룹의 반들 평균 하기
SELECT SUBSTR(sc_num,1,4) AS 반, ROUND(AVG(sc_kor + sc_eng + sc_math) / 3) -- 반평균
FROM tbl_score
GROUP BY SUBSTR(sc_num,1,4)
HAVING SUBSTR(sc_num,1,4) <= '2005'
ORDER BY 반;
-- HAVING과 WHERE
-- 두가지 모두 결과를 SELECTION하는 조건문을 설정하는 방식이다
-- HAVING은 그룹으로 묶이거나 통계함수로 연산된 결과를 조건으로 설정하는 방식이고
-- WHERE 아무런 연산이 수행되기 전에 원본 데이터를 조건으로 제한하는 방식이다.
-- 어쩔수 없이 통계결과를 제한할때는 HAVING을 써야한다.
-- WHERE절에 조건을 설정하여 데이터를 제한한 후 연산을 수행할수 있다면
-- 항상 그 방법을 우선 조건으로 설정하자
-- HAVING은 WHERE 조건이 없으면 전체데이터를 상대로 상당한 연산을 수행한 후
-- 조건을 설정하므로 상대적으로 WHERE 조건을 설정하는 것 보다 느리다.
SELECT SUBSTR(sc_num,1,4) AS 반, ROUND(AVG(sc_kor + sc_eng + sc_math) / 3) -- 반평균
FROM tbl_score
WHERE SUBSTR(sc_num,1,4) <= '2005'
GROUP BY SUBSTR(sc_num,1,4)
ORDER BY 반;
SELECT st_name FROM tbl_student;
|
/* 格式化对象 2019/10/31 17:18:21 (QP5 v5.287) */
DECLARE
Seq INT;
BEGIN
FOR i IN 1 .. 40
LOOP
FOR it
IN ( SELECT id,
wavecode,
A,
ROWNUM AS rn
FROM test
WHERE wavecode = 1
AND TO_NUMBER (A) > 240
AND TO_NUMBER (A) <= 280 -- IS NOT NULL
AND TO_NUMBER (REPLACE (itemname, '3A-', '')) = i
ORDER BY id)
LOOP
UPDATE test
SET orderno =
'O20191031-'
|| it.A
|| '-'
|| it.wavecode
|| '-'
|| LPAD (i, 2, '0'),
DETAILORDERNO =
'O20191031-'
|| it.A
|| '-'
|| it.wavecode
|| '-'
|| LPAD (i, 2, '0')
|| '-'
|| LPAD (it.rn, 4, '0')
WHERE id = it.id;
DBMS_OUTPUT.put_line (
'O20191031-'
|| it.A
|| '-'
|| it.wavecode
|| '-'
|| LPAD (i, 2, '0')
|| ' '
|| 'O20191031-'
|| it.A
|| '-'
|| it.wavecode
|| '-'
|| LPAD (i, 2, '0')
|| '-'
|| LPAD (it.rn, 4, '0'));
END LOOP;
END LOOP;
END;
SELECT DETAILORDERNO,
TO_NUMBER (SUBSTR (DETAILORDERNO, 16, 4)),
TRUNC (TO_NUMBER (SUBSTR (DETAILORDERNO, 16, 4)) / 50),
TRUNC (TO_NUMBER (SUBSTR (DETAILORDERNO, 16, 4)) / 50) + 1,
orderno
|| '-'
|| (TRUNC (TO_NUMBER (SUBSTR (DETAILORDERNO, 16, 4)) / 50) + 1)
FROM test
WHERE wavecode = '1' AND areacode IS NULL;
UPDATE test
SET STOCKUNITCODE='PCS',STOCKUNITNAME='箱',SPEC='1*6'
WHERE wavecode = '1';
--UPDATE test
-- SET orderno =
-- orderno
-- || '-'
-- || (TRUNC (TO_NUMBER (SUBSTR (DETAILORDERNO, 16, 4)) / 50) + 1)
-- WHERE wavecode = '1' AND areacode IS NULL;
/* 格式化对象 2019/10/31 17:37:01 (QP5 v5.287) */
--INSERT INTO DPS_OUTBOUNDDETAIL (ID,
-- ORDERNO,
-- DETAILORDERNO,
-- STOCKQTY,
-- QTY,
-- ITEMCODE,
-- AREACODE,
-- LOCATIONCODE,
-- STATUS,
-- STOCKUNITCODE,
-- STOCKUNITNAME,
-- UNITCODE,
-- UNITNAME,
-- CUSTOMCODE,
-- CUSTOMNAME,
-- WAVECODE,
-- SPEC,
-- DEALQTY)
-- SELECT ID,
-- ORDERNO,
-- DETAILORDERNO,
-- STOCKQTY,
-- QTY,
-- ITEMCODE,
-- AREACODE,
-- LOCATIONCODE,
-- STATUS,
-- STOCKUNITCODE,
-- STOCKUNITNAME,
-- UNITCODE,
-- UNITNAME,
-- CUSTOMCODE,
-- CUSTOMNAME,
-- WAVECODE,
-- SPEC,
-- DEALQTY
-- FROM test
-- WHERE wavecode = 1;
/* 格式化对象 2019/11/01 08:58:14 (QP5 v5.287) */
--INSERT INTO DPS_ITEMUNIT (CODE,
-- name,
-- ITEMCODE,
-- INNERCODE,
-- qty,
-- ID)
-- SELECT CODE,
-- name,
-- ITEMCODE,
-- INNERCODE,
-- qty,
-- SYS_GUID ()
-- FROM (SELECT DISTINCT 'PCS' AS CODE,
-- '箱' AS name,
-- itemcode,
-- 'BT' AS INNERCODE,
-- 6 AS QTY
-- FROM DPS_OUTBOUNDDETAIL
-- UNION ALL
-- SELECT DISTINCT 'BT' AS CODE,
-- '瓶' AS name,
-- itemcode,
-- '' AS INNERCODE,
-- null AS QTY
-- FROM DPS_OUTBOUNDDETAIL); |
--Crie uma Store Procedure, cujo parâmetro de entrada seja o código IBGE7 do Município, e retorno um RESULTSET contendo:
--- Nome do Estado
--
--- Nome do Mesoregião
--
--- Nome do Microregião
--
--- CEP.
CREATE PROCEDURE sp_PesquisarPorIBGE7EstadoMesoregiaoMicroregiaoCEP
(
@IBGE7 INT
)
AS
SELECT
UFS.Descricao AS Estado,
MES.Descricao AS NomeMesoregiao,
MIC.Descricao AS NomeMicroregiao,
MUN.CEP
FROM Municipio AS MUN
INNER JOIN Mesoregiao AS MES
ON MUN.MesoregiaoID = MES.MesoregiaoID
INNER JOIN Microregiao AS MIC
ON MUN.MicroregiaoID = MIC.MicroregiaoID
INNER JOIN UnidadesFederacao AS UFS
ON MUN.UFID = UFS.UFID
WHERE MUN.IBGE7 = @IBGE7; |
-- table creation
create table departments (
id serial primary key,
name varchar(200)
);
create table employees (
id serial primary key,
name varchar(200),
department_id int references departments(id)
);
-- data filling
insert into departments(name) values('dep1'), ('dep2'), ('dep3');
insert into employees(name, department_id) values ('Emp11', 1), ('Emp12', 1), ('Emp21', 2), ('NoDepEmp', null);
-- selects with different joins
select * from departments d left join employees e on d.id = e.department_id;
select * from departments d right join employees e on d.id = e.department_id;
select * from departments d full join employees e on d.id = e.department_id;
-- select employees without department
select e.name from employees e left join departments d on e.department_id = d.id where d.id is null;
-- the same result with different joins
select * from employees e left join departments d on e.department_id = d.id;
select * from departments d right join employees e on e.department_id = d.id;
|
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50532
Source Host : localhost:3306
Source Database : db_crm
Target Server Type : MYSQL
Target Server Version : 50532
File Encoding : 65001
Date: 2016-12-03 11:08:01
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for t_cus_dev_plan
-- ----------------------------
DROP TABLE IF EXISTS `t_cus_dev_plan`;
CREATE TABLE `t_cus_dev_plan` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`saleChanceId` int(11) DEFAULT NULL,
`planItem` varchar(100) DEFAULT NULL,
`planDate` date DEFAULT NULL,
`exeAffect` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_t_cus_dev_plan` (`saleChanceId`),
CONSTRAINT `FK_t_cus_dev_plan` FOREIGN KEY (`saleChanceId`) REFERENCES `t_sale_chance` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_cus_dev_plan
-- ----------------------------
INSERT INTO `t_cus_dev_plan` VALUES ('1', '1', '测试计划项', '2011-01-01', '好');
INSERT INTO `t_cus_dev_plan` VALUES ('4', '1', 'haha', '2015-05-20', 'en啊');
INSERT INTO `t_cus_dev_plan` VALUES ('5', '1', 'ss', '2015-05-13', '');
INSERT INTO `t_cus_dev_plan` VALUES ('6', '16', '2121', '2015-05-28', '');
INSERT INTO `t_cus_dev_plan` VALUES ('7', '16', '21121', '2015-05-19', '');
INSERT INTO `t_cus_dev_plan` VALUES ('8', '19', '21', '2015-05-28', '');
INSERT INTO `t_cus_dev_plan` VALUES ('9', '2', '1', '2015-05-27', '2');
INSERT INTO `t_cus_dev_plan` VALUES ('10', '2', '2', '2015-05-28', '');
INSERT INTO `t_cus_dev_plan` VALUES ('11', '21', '好', '2015-06-09', '额');
INSERT INTO `t_cus_dev_plan` VALUES ('12', '22', '联系客户,介绍产品', '2015-06-01', '有点效果');
INSERT INTO `t_cus_dev_plan` VALUES ('13', '22', '请客户吃饭,洽谈', '2015-06-07', '成功了');
INSERT INTO `t_cus_dev_plan` VALUES ('15', '2', '方法', '2016-06-24', '实得分');
INSERT INTO `t_cus_dev_plan` VALUES ('16', '2', '方法', '2016-06-24', '实得分');
-- ----------------------------
-- Table structure for t_customer
-- ----------------------------
DROP TABLE IF EXISTS `t_customer`;
CREATE TABLE `t_customer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`khno` varchar(20) DEFAULT NULL,
`name` varchar(20) DEFAULT NULL,
`area` varchar(20) DEFAULT NULL,
`cusManager` varchar(20) DEFAULT NULL,
`level` varchar(30) DEFAULT NULL,
`myd` varchar(30) DEFAULT NULL,
`xyd` varchar(30) DEFAULT NULL,
`address` varchar(500) DEFAULT NULL,
`postCode` varchar(50) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
`fax` varchar(20) DEFAULT NULL,
`webSite` varchar(20) DEFAULT NULL,
`yyzzzch` varchar(50) DEFAULT NULL,
`fr` varchar(20) DEFAULT NULL,
`zczj` varchar(20) DEFAULT NULL,
`nyye` varchar(20) DEFAULT NULL,
`khyh` varchar(50) DEFAULT NULL,
`khzh` varchar(50) DEFAULT NULL,
`dsdjh` varchar(50) DEFAULT NULL,
`gsdjh` varchar(50) DEFAULT NULL,
`state` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_customer
-- ----------------------------
INSERT INTO `t_customer` VALUES ('1', 'KH21321321', '北京大牛科技', '北京', '小张', '战略合作伙伴', '☆☆☆', '☆☆☆', '北京海淀区双榆树东里15号', '100027', '010-62263393', '010-62263393', 'www.daniu.com', '420103000057404', '张三', '1000', '5000', '中国银行 ', '6225231243641', '4422214321321', '4104322332', '0');
INSERT INTO `t_customer` VALUES ('16', 'KH20150526073022', '风驰科技', '北京', '小红', '大客户', '☆', '☆', '321', '21', '321', '321', '321', '321', '321', '', '21', '321', '321', '321', '3213', '0');
INSERT INTO `t_customer` VALUES ('17', 'KH20150526073023', '巨人科技', null, '小丽', '普通客户', null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, '0');
INSERT INTO `t_customer` VALUES ('19', 'KH20150526073025', '好人集团', null, null, '合作伙伴', null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
INSERT INTO `t_customer` VALUES ('20', 'KH20150526073026', '新浪', null, null, '大客户', null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
-- ----------------------------
-- Table structure for t_customer_contact
-- ----------------------------
DROP TABLE IF EXISTS `t_customer_contact`;
CREATE TABLE `t_customer_contact` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cusId` int(11) DEFAULT NULL,
`contactTime` date DEFAULT NULL,
`address` varchar(500) DEFAULT NULL,
`overview` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_t_customer_contact` (`cusId`),
CONSTRAINT `FK_t_customer_contact` FOREIGN KEY (`cusId`) REFERENCES `t_customer` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_customer_contact
-- ----------------------------
INSERT INTO `t_customer_contact` VALUES ('1', '1', '2015-05-14', '1', '2');
INSERT INTO `t_customer_contact` VALUES ('2', '1', '2015-05-06', '1', '2');
-- ----------------------------
-- Table structure for t_customer_linkman
-- ----------------------------
DROP TABLE IF EXISTS `t_customer_linkman`;
CREATE TABLE `t_customer_linkman` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cusId` int(11) DEFAULT NULL,
`linkName` varchar(20) DEFAULT NULL,
`sex` varchar(20) DEFAULT NULL,
`zhiwei` varchar(50) DEFAULT NULL,
`officePhone` varchar(50) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_t_customer_linkman` (`cusId`),
CONSTRAINT `FK_t_customer_linkman` FOREIGN KEY (`cusId`) REFERENCES `t_customer` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_customer_linkman
-- ----------------------------
INSERT INTO `t_customer_linkman` VALUES ('1', '1', '1', '男', '321', '321', '21321');
INSERT INTO `t_customer_linkman` VALUES ('2', '1', '2', '女', '21', '321', '321');
INSERT INTO `t_customer_linkman` VALUES ('4', '1', '3', '女', '4', '5', '6');
INSERT INTO `t_customer_linkman` VALUES ('5', '1', '33', '男', '44', '55', '66');
INSERT INTO `t_customer_linkman` VALUES ('6', '1', '张三', '男', '经理', '21321', '32132121');
INSERT INTO `t_customer_linkman` VALUES ('7', '1', '是', '女', '发送', '2321', '321321');
INSERT INTO `t_customer_linkman` VALUES ('8', '17', '001', '男', '001', '00101010', '0101010101');
-- ----------------------------
-- Table structure for t_customer_loss
-- ----------------------------
DROP TABLE IF EXISTS `t_customer_loss`;
CREATE TABLE `t_customer_loss` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cusNo` varchar(40) DEFAULT NULL,
`cusName` varchar(20) DEFAULT NULL,
`cusManager` varchar(20) DEFAULT NULL,
`lastOrderTime` date DEFAULT NULL,
`confirmLossTime` date DEFAULT NULL,
`state` int(11) DEFAULT NULL,
`lossreason` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_customer_loss
-- ----------------------------
INSERT INTO `t_customer_loss` VALUES ('1', '1', '大风科技', '小张', '2015-02-01', '2014-05-01', '1', '11');
INSERT INTO `t_customer_loss` VALUES ('3', 'KH20150526073022', '鸟人科技', '小红', '2014-02-02', '2014-05-01', '1', '公司迁地址');
INSERT INTO `t_customer_loss` VALUES ('4', 'KH20150526073023', '321', '小丽', '2014-02-03', null, '1', null);
-- ----------------------------
-- Table structure for t_customer_order
-- ----------------------------
DROP TABLE IF EXISTS `t_customer_order`;
CREATE TABLE `t_customer_order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cusId` int(11) DEFAULT NULL,
`orderNo` varchar(40) DEFAULT NULL,
`orderDate` date DEFAULT NULL,
`address` varchar(200) DEFAULT NULL,
`state` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_t_customer_order` (`cusId`),
CONSTRAINT `FK_t_customer_order` FOREIGN KEY (`cusId`) REFERENCES `t_customer` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_customer_order
-- ----------------------------
INSERT INTO `t_customer_order` VALUES ('1', '1', 'DD11213', '2015-02-01', '11', '1');
INSERT INTO `t_customer_order` VALUES ('2', '16', 'DD11212', '2014-01-02', '22', '1');
INSERT INTO `t_customer_order` VALUES ('3', '16', 'DD21321', '2014-02-02', '22', '1');
INSERT INTO `t_customer_order` VALUES ('4', '17', 'DD2121', '2014-02-03', 'ss', '1');
-- ----------------------------
-- Table structure for t_customer_reprieve
-- ----------------------------
DROP TABLE IF EXISTS `t_customer_reprieve`;
CREATE TABLE `t_customer_reprieve` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lossId` int(11) DEFAULT NULL,
`measure` varchar(500) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_t_customer_reprieve` (`lossId`),
CONSTRAINT `FK_t_customer_reprieve` FOREIGN KEY (`lossId`) REFERENCES `t_customer_loss` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_customer_reprieve
-- ----------------------------
INSERT INTO `t_customer_reprieve` VALUES ('1', '1', '打电话给客户,询问不卖我司产品原因2');
INSERT INTO `t_customer_reprieve` VALUES ('2', '1', '发送我司最新产品给客户');
INSERT INTO `t_customer_reprieve` VALUES ('3', '1', 's');
INSERT INTO `t_customer_reprieve` VALUES ('4', '4', '多发');
INSERT INTO `t_customer_reprieve` VALUES ('5', '4', '2121');
-- ----------------------------
-- Table structure for t_customer_service
-- ----------------------------
DROP TABLE IF EXISTS `t_customer_service`;
CREATE TABLE `t_customer_service` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`serveType` varchar(30) DEFAULT NULL,
`overview` varchar(500) DEFAULT NULL,
`customer` varchar(30) DEFAULT NULL,
`state` varchar(20) DEFAULT NULL,
`servicerequest` varchar(500) DEFAULT NULL,
`createPeople` varchar(100) DEFAULT NULL,
`createTime` datetime DEFAULT NULL,
`assigner` varchar(100) DEFAULT NULL,
`assignTime` datetime DEFAULT NULL,
`serviceProce` varchar(500) DEFAULT NULL,
`serviceProcePeople` varchar(20) DEFAULT NULL,
`serviceProceTime` datetime DEFAULT NULL,
`serviceProceResult` varchar(500) DEFAULT NULL,
`myd` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_customer_service
-- ----------------------------
INSERT INTO `t_customer_service` VALUES ('1', '咨询', '咨询下Think pad价格', '大浪技术', '已归档', '。。。测试', 'Jack', '2015-06-03 00:00:00', '小红', '2015-06-03 00:00:00', 's', 'Jack', '2015-06-04 00:00:00', 'OK', '☆☆☆☆');
INSERT INTO `t_customer_service` VALUES ('2', '咨询', '321', '1', '已归档', '321', 'Jack', '2015-06-03 00:00:00', null, null, 'sss', 'Jack', '2015-06-04 00:00:00', 'OK', '☆☆☆');
INSERT INTO `t_customer_service` VALUES ('3', '咨询', '21', '21', '已归档', '1', 'Jack', '2015-06-03 00:00:00', '小红', '2015-06-03 00:00:00', 'sds', 'Jack', '2015-06-04 00:00:00', 'OK', '☆☆☆☆');
INSERT INTO `t_customer_service` VALUES ('6', '咨询', '321', '21', '已归档', '321', 'Jack', '2015-06-03 00:00:00', '小红', '2015-06-04 00:00:00', 'ds', 'Jack', '2015-06-04 00:00:00', 'OK', '☆☆☆');
INSERT INTO `t_customer_service` VALUES ('7', '咨询', 's', '222', '已归档', 'ss', 'Jack', '2015-06-04 00:00:00', '小明', '2015-06-04 00:00:00', 'ss', 'Jack', '2015-06-04 00:00:00', 'OK', '☆☆');
INSERT INTO `t_customer_service` VALUES ('8', '建议', '4', '3', '已处理', '5', 'Jack', '2015-06-04 00:00:00', '小张', '2015-06-04 00:00:00', '111', 'Jack', '2015-06-04 00:00:00', null, null);
INSERT INTO `t_customer_service` VALUES ('9', '投诉', '2', '1', '已归档', '3', 'Jack', '2015-06-04 00:00:00', '小明', '2015-06-04 00:00:00', '333', 'Jack', '2015-06-04 00:00:00', 'OK', '☆☆☆☆☆');
INSERT INTO `t_customer_service` VALUES ('10', '建议', '32', '32', '新创建', '32', 'Jack', '2015-06-04 00:00:00', null, null, null, null, null, null, null);
INSERT INTO `t_customer_service` VALUES ('11', '建议', '21', '21', '新创建', '21', 'Jack', '2015-06-04 00:00:00', null, null, null, null, null, null, null);
INSERT INTO `t_customer_service` VALUES ('12', '建议', 'fda', '大牛科技', '已归档', 'fda', 'Jack', '2015-06-10 00:00:00', '小红', '2015-06-10 00:00:00', 'fda', 'Jack', '2015-06-10 00:00:00', 'good', '☆☆☆☆☆');
INSERT INTO `t_customer_service` VALUES ('13', '咨询', '咨询下Think pad价格。。', '大众科技', '已归档', '发达龙卷风大。。。。', 'Jack', '2015-06-11 00:00:00', '小红', '2015-06-11 00:00:00', '。。。\r\n1,2\r\n,3。。。', 'Jack', '2015-06-11 00:00:00', 'OK', '☆☆☆☆☆');
INSERT INTO `t_customer_service` VALUES ('14', '投诉', '你敲诈我', '小心', '新创建', '杀了他', 'Jack', '2016-06-25 00:00:00', null, null, null, null, null, null, null);
INSERT INTO `t_customer_service` VALUES ('15', '咨询', '111111', '小张', '新创建', '11111111', 'Jack', '2016-06-26 00:00:00', null, null, null, null, null, null, null);
-- ----------------------------
-- Table structure for t_datadic
-- ----------------------------
DROP TABLE IF EXISTS `t_datadic`;
CREATE TABLE `t_datadic` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dataDicName` varchar(50) DEFAULT NULL,
`dataDicValue` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_t_datadic` (`dataDicValue`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_datadic
-- ----------------------------
INSERT INTO `t_datadic` VALUES ('1', '客户等级', '普通客户');
INSERT INTO `t_datadic` VALUES ('2', '客户等级', '重点开发客户');
INSERT INTO `t_datadic` VALUES ('3', '客户等级', '大客户');
INSERT INTO `t_datadic` VALUES ('4', '客户等级', '合作伙伴');
INSERT INTO `t_datadic` VALUES ('5', '客户等级', '战略合作伙伴');
INSERT INTO `t_datadic` VALUES ('6', '服务类型', '咨询');
INSERT INTO `t_datadic` VALUES ('7', '服务类型', '建议');
INSERT INTO `t_datadic` VALUES ('8', '服务类型', '投诉');
-- ----------------------------
-- Table structure for t_order_details
-- ----------------------------
DROP TABLE IF EXISTS `t_order_details`;
CREATE TABLE `t_order_details` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`orderId` int(11) DEFAULT NULL,
`goodsName` varchar(100) DEFAULT NULL,
`goodsNum` int(11) DEFAULT NULL,
`unit` varchar(20) DEFAULT NULL,
`price` float DEFAULT NULL,
`sum` float DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_t_order_details` (`orderId`),
CONSTRAINT `FK_t_order_details` FOREIGN KEY (`orderId`) REFERENCES `t_customer_order` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_order_details
-- ----------------------------
INSERT INTO `t_order_details` VALUES ('1', '1', '联想笔记本', '2', '台', '4900', '9800');
INSERT INTO `t_order_details` VALUES ('2', '1', '惠普音响', '4', '台', '200', '800');
INSERT INTO `t_order_details` VALUES ('3', '2', '罗技键盘', '10', '个', '90', '900');
INSERT INTO `t_order_details` VALUES ('4', '3', '艾利鼠标', '20', '个', '20', '400');
INSERT INTO `t_order_details` VALUES ('5', '3', '东芝U盘', '5', '个', '105', '525');
INSERT INTO `t_order_details` VALUES ('6', '4', '充电器', '1', '个', '30', '30');
-- ----------------------------
-- Table structure for t_product
-- ----------------------------
DROP TABLE IF EXISTS `t_product`;
CREATE TABLE `t_product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`productName` varchar(100) DEFAULT NULL,
`model` varchar(50) DEFAULT NULL,
`unit` varchar(20) DEFAULT NULL,
`price` float DEFAULT NULL,
`store` int(11) DEFAULT NULL,
`remark` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_product
-- ----------------------------
INSERT INTO `t_product` VALUES ('1', '联想笔记本', 'Y450', '台', '4500', '120', '好');
-- ----------------------------
-- Table structure for t_sale_chance
-- ----------------------------
DROP TABLE IF EXISTS `t_sale_chance`;
CREATE TABLE `t_sale_chance` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`chanceSource` varchar(300) DEFAULT NULL,
`customerName` varchar(100) DEFAULT NULL,
`cgjl` int(11) DEFAULT NULL,
`overview` varchar(300) DEFAULT NULL,
`linkMan` varchar(100) DEFAULT NULL,
`linkPhone` varchar(100) DEFAULT NULL,
`description` varchar(1000) DEFAULT NULL,
`createMan` varchar(100) DEFAULT NULL,
`createTime` datetime DEFAULT NULL,
`assignMan` varchar(100) DEFAULT NULL,
`assignTime` datetime DEFAULT NULL,
`state` int(11) DEFAULT NULL,
`devResult` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_sale_chance
-- ----------------------------
INSERT INTO `t_sale_chance` VALUES ('1', '主动来找的', '风软科技', '100', '采购笔记本意向', '张先生', '137234576543', '。。。', 'Jack', '2014-01-01 00:00:00', '3', '2015-05-24 16:15:00', '1', '2');
INSERT INTO `t_sale_chance` VALUES ('2', '', '1', '12', '', '', '', '', '12', null, '3', '2015-05-25 11:21:00', '1', '1');
INSERT INTO `t_sale_chance` VALUES ('8', null, '7', null, null, null, null, null, null, null, null, null, '0', '0');
INSERT INTO `t_sale_chance` VALUES ('9', null, '8', null, null, null, null, null, null, null, null, null, '0', '0');
INSERT INTO `t_sale_chance` VALUES ('10', null, '9', null, null, null, null, null, null, null, null, null, '0', '0');
INSERT INTO `t_sale_chance` VALUES ('11', '', '10', '1', '', '', '', '', '321', null, '', null, '0', '0');
INSERT INTO `t_sale_chance` VALUES ('13', '', '21', '1', '', '', '', '', '21', null, '3', null, '0', '0');
INSERT INTO `t_sale_chance` VALUES ('14', '2', '1', '5', '6', '3', '4', '7', '8', null, '3', null, '0', '0');
INSERT INTO `t_sale_chance` VALUES ('15', '213', '112', '22', '', '', '', '', '221', '2013-01-01 11:20:00', '3', '2013-01-01 11:20:00', '1', '1');
INSERT INTO `t_sale_chance` VALUES ('16', '22', '11', '55', '66', '33', '44', '77', '88', '2013-01-01 11:20:00', '4', '2013-01-01 11:20:00', '1', '3');
INSERT INTO `t_sale_chance` VALUES ('17', '321', '121', '1', '321', '321', '213', '321', '321', '2015-05-22 11:23:00', '3', null, '0', '0');
INSERT INTO `t_sale_chance` VALUES ('18', '321', '321', '11', '321', '321', '213', '321', 'Jack', '2015-05-22 11:43:00', '', null, '0', '0');
INSERT INTO `t_sale_chance` VALUES ('19', '321', '213', '21', '21', '21', '321', '321', 'Jack', '2015-05-24 11:33:00', '3', '2015-05-24 11:34:00', '1', '3');
INSERT INTO `t_sale_chance` VALUES ('20', '321', '213', '100', '321', '321', '321', '321', 'Jack', '2015-05-24 11:35:00', '', null, '0', '0');
INSERT INTO `t_sale_chance` VALUES ('21', '行业介绍', '大鸟爱科技', '80', '阿凡达深刻理解', '张先生', '0231-321321', '发达放大空间发大水发大水了发', 'Jack', '2015-06-10 16:32:00', '4', '2015-06-10 16:33:00', '1', '3');
INSERT INTO `t_sale_chance` VALUES ('22', '同行介绍', '鸟人科技', '90', '采购IBM服务器意向', '张三', '2321321321', ',...', 'Jack', '2015-06-11 08:35:00', '5', '2015-06-11 08:36:00', '1', '2');
INSERT INTO `t_sale_chance` VALUES ('23', '网络', '小薇', '55', '这个该要', '小子', '15236312356', '很有可能', 'Jack', '2016-06-23 09:57:00', '5', '2016-06-23 09:59:00', '1', '0');
-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`trueName` varchar(20) DEFAULT NULL,
`email` varchar(30) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
`roleName` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('1', 'java1234', '12', 'Jack', 'java1234@qq.com', '123456789', '系统管理员');
INSERT INTO `t_user` VALUES ('2', 'json1234', '123', 'Json', 'json@qq.com', '232132121', '销售主管');
INSERT INTO `t_user` VALUES ('3', 'xiaoming', '123', '小明', 'khjl01@qq.com', '2321321', '客户经理');
INSERT INTO `t_user` VALUES ('4', 'xiaohong', '123', '小红', 'khjl02@qq.com', '21321', '客户经理');
INSERT INTO `t_user` VALUES ('5', 'xiaozhang', '123', '小张', 'khjl03@qq.com', '3242323', '客户经理');
INSERT INTO `t_user` VALUES ('6', 'daqian', '123', '曹大千', 'gaoguan@qq.com', '5434232', '高管');
INSERT INTO `t_user` VALUES ('7', '21', '321', '321321', '321@qq.com', '321', '系统管理员');
INSERT INTO `t_user` VALUES ('9', '21', '32132', '321', '321@qq.com', '321', '销售主管');
|
-- run these codes if you want to restart the database
-- drop the databse
DROP DATABASE IF EXISTS foodfy;
-- delete all tables contents
DELETE FROM chefs;
DELETE FROM files;
DELETE FROM recipe_files;
DELETE FROM recipes;
DELETE FROM users;
ALTER SEQUENCE chefs_id_seq RESTART WITH 1;
ALTER SEQUENCE files_id_seq RESTART WITH 1;
ALTER SEQUENCE recipe_files_id_seq RESTART WITH 1;
ALTER SEQUENCE recipes_id_seq RESTART WITH 1;
ALTER SEQUENCE users_id_seq RESTART WITH 1; |
--Problem 1. Employee Address
--Write a query that selects:
-- EmployeeId
-- JobTitle
-- AddressId
-- AddressText
--Return the first 5 rows sorted by AddressId in ascending order.
SELECT TOP (5) emp.EmployeeID,
emp.JobTitle,
adr.AddressID,
adr.AddressText
FROM Employees AS emp
JOIN Addresses AS adr ON adr.AddressID = emp.AddressID
ORDER BY emp.AddressID;
--Problem 2. Addresses with Towns
--Write a query that selects:
-- FirstName
-- LastName
-- Town
-- AddressText
--Sorted by FirstName in ascending order then by LastName. Select first 50 employees.
SELECT TOP (50) emp.FirstName,
emp.LastName,
t.[Name],
adr.AddressText
FROM Employees AS emp
JOIN Addresses AS adr ON adr.AddressID = emp.AddressID
JOIN Towns AS t ON t.TownID = adr.TownID
ORDER BY emp.FirstName,
emp.LastName;
--Problem 3. Sales Employee
--Write a query that selects:
-- EmployeeID
-- FirstName
-- LastName
-- DepartmentName
--Sorted by EmployeeID in ascending order. Select only employees from Sales department.
SELECT emp.EmployeeID,
emp.FirstName,
emp.LastName,
dept.[Name]
FROM Employees AS emp
JOIN Departments AS dept ON dept.DepartmentID = emp.DepartmentID
WHERE dept.[Name] = 'Sales'
ORDER BY emp.EmployeeID;
--Problem 4. Employee Departments
--Write a query that selects:
-- EmployeeID
-- FirstName
-- Salary
-- DepartmentName
--Filter only employees with salary higher than 15000. Return the first 5 rows sorted by DepartmentID in ascending order.
SELECT TOP (5) EmployeeID,
FirstName,
Salary,
dept.[Name]
FROM Employees AS emp
JOIN Departments AS dept ON dept.DepartmentID = emp.DepartmentID
WHERE Salary > 15000
ORDER BY dept.DepartmentID;
--Problem 5. Employees Without Project
--Write a query that selects:
-- EmployeeID
-- FirstName
--Filter only employees without a project. Return the first 3 rows sorted by EmployeeID in ascending order.
SELECT TOP (3) e.EmployeeID,
e.FirstName
FROM Employees AS e
FULL JOIN EmployeesProjects AS ep ON ep.EmployeeID = e.EmployeeID
WHERE ep.EmployeeID IS NULL;
--Problem 6. Employees Hired After
--Write a query that selects:
-- FirstName
-- LastName
-- HireDate
-- DeptName
--Filter only employees hired after 1.1.1999 and are from either "Sales" or "Finance" departments, sorted by HireDate (ascending).
SELECT FirstName,
LastName,
HireDate,
dept.[Name]
FROM Employees AS emp
JOIN Departments AS dept ON dept.DepartmentID = emp.DepartmentID
WHERE HireDate > '01.01.1999'
AND dept.[Name] = 'Sales'
OR dept.[Name] = 'Finance'
ORDER BY HireDate;
--Problem 7. Employees with Project
--Write a query that selects:
-- EmployeeID
-- FirstName
-- ProjectName
--Filter only employees with a project which has started after 13.08.2002 and it is still ongoing (no end date). Return the first 5 rows sorted by EmployeeID in ascending order.
SELECT TOP 5 e.EmployeeID,
e.FirstName,
p.Name
FROM Employees AS e
JOIN EmployeesProjects AS ep ON ep.EmployeeID = e.EmployeeID
JOIN Projects AS p ON p.ProjectID = ep.ProjectID
WHERE p.StartDate > CONVERT(DATE, '13.08.2002', 104)
AND p.EndDate IS NULL
ORDER BY e.EmployeeID;
--Problem 8. Employee 24
--Write a query that selects:
-- EmployeeID
-- FirstName
-- ProjectName
--Filter all the projects of employee with Id 24. If the project has started during or after 2005 the returned value should be NULL.
SELECT e.EmployeeID,
FirstName,
CASE
WHEN YEAR(p.StartDate) >= '2005'
THEN NULL
ELSE p.Name
END AS [ProjectName]
FROM Employees AS e
JOIN EmployeesProjects AS ep ON e.EmployeeID = ep.EmployeeID
JOIN Projects AS p ON p.ProjectID = ep.ProjectID
WHERE ep.EmployeeID = 24;
--Problem 9. Employee Manager
--Write a query that selects:
-- EmployeeID
-- FirstName
-- ManagerID
-- ManagerName
--Filter all employees with a manager who has ID equals to 3 or 7. Return all the rows, sorted by EmployeeID in ascending order.
SELECT e.EmployeeID,
e.FirstName,
e.ManagerID,
m.FirstName
FROM Employees AS e
JOIN Employees AS m ON e.ManagerID = m.EmployeeID
WHERE m.EmployeeID IN(3, 7)
ORDER BY e.EmployeeID;
--Problem 10. Employee Summary
--Write a query that selects:
-- EmployeeID
-- EmployeeName
-- ManagerName
-- DepartmentName
--Show first 50 employees with their managers and the departments they are in (show the departments of the employees). Order by EmployeeID.
SELECT TOP 50 e.EmployeeID,
e.FirstName + ' ' + e.LastName AS EmployeeName,
m.FirstName + ' ' + m.LastName AS ManagerName,
d.Name
FROM Employees AS e
JOIN Employees AS m ON e.ManagerID = m.EmployeeID
JOIN Departments AS d ON e.DepartmentID = d.DepartmentID
ORDER BY e.EmployeeID;
--Problem 11. Min Average Salary
--Write a query that returns the value of the lowest average salary of all departments.
SELECT MIN(t.AVGSALARY) AS MinAverageSalary
FROM
(
SELECT AVG(Salary) AS AVGSALARY
FROM Employees AS emp
GROUP BY DepartmentID
) AS t;
--Problem 12. Highest Peaks in Bulgaria
--Write a query that selects:
-- CountryCode
-- MountainRange
-- PeakName
-- Elevation
--Filter all peaks in Bulgaria with elevation over 2835. Return all the rows sorted by elevation in descending order.
SELECT c.CountryCode,
m.MountainRange,
p.PeakName,
p.Elevation
FROM Countries AS c
JOIN MountainsCountries AS mc ON c.CountryCode = mc.CountryCode
JOIN Mountains AS m ON mc.MountainId = m.Id
JOIN Peaks AS p ON m.Id = p.MountainId
WHERE p.Elevation > 2835
AND c.CountryCode = 'BG'
ORDER BY p.Elevation DESC;
--Problem 13. Count Mountain Ranges
--Write a query that selects:
-- CountryCode
-- MountainRanges
--Filter the count of the mountain ranges in the United States, Russia and Bulgaria.
SELECT CountryCode,
COUNT(*) AS [Range]
FROM Mountains AS m
JOIN MountainsCountries AS mc ON m.Id = mc.MountainId
WHERE CountryCode IN('BG', 'RU', 'US')
GROUP BY CountryCode;
--Problem 14. Countries with Rivers
--Write a query that selects:
-- CountryName
-- RiverName
--Find the first 5 countries with or without rivers in Africa. Sort them by CountryName in ascending order.
SELECT TOP 5 CountryName,
r.RiverName
FROM Countries AS c
LEFT JOIN CountriesRivers AS cr ON c.CountryCode = cr.CountryCode
LEFT JOIN Rivers AS r ON r.Id = cr.RiverId
WHERE ContinentCode = 'AF'
ORDER BY CountryName;
--Problem 15. *Continents and Currencies
--Write a query that selects:
-- ContinentCode
-- CurrencyCode
-- CurrencyUsage
--Find all continents and their most used currency. Filter any currency that is used in only one country. Sort your results by ContinentCode.
SELECT k.ContinentCode,
k.CurrencyCode,
k.CurrencyUsage
FROM
(
SELECT c.ContinentCode,
c.CurrencyCode,
COUNT(c.CurrencyCode) AS CurrencyUsage,
DENSE_RANK() OVER(PARTITION BY c.ContinentCode
ORDER BY COUNT(c.CurrencyCode) DESC) AS CurrencyRank
FROM Countries AS c
GROUP BY c.ContinentCode,
c.CurrencyCode
HAVING COUNT(c.CurrencyCode) > 1
) AS k
WHERE k.CurrencyRank = 1
ORDER BY k.ContinentCode;
--Problem 16. Countries without any Mountains
--Write a query that selects CountryCode. Find all the count of all countries, which dont have a mountain.
SELECT COUNT(*) AS CountryCode
FROM
(
SELECT m.Id
FROM Countries AS c
LEFT JOIN MountainsCountries AS mc ON mc.CountryCode = c.CountryCode
LEFT JOIN Mountains AS m ON m.Id = mc.MountainId
WHERE m.Id IS NULL
) AS k;
--Problem 17. Highest Peak and Longest River by Country
--For each country, find the elevation of the highest peak and the length of the longest river, sorted by the highest peak elevation (from highest to lowest),
-- then by the longest river length (from longest to smallest),
-- then by country name (alphabetically).
--Display NULL when no data is available in some of the columns. Limit only the first 5 rows.
SELECT TOP 5 c.CountryName,
MAX(p.Elevation) AS HighestPeakElevation,
MAX(r.Length) AS LongestRiverLength
FROM Countries AS c
JOIN CountriesRivers AS cr ON cr.CountryCode = c.CountryCode
JOIN Rivers AS r ON r.Id = cr.RiverId
JOIN MountainsCountries AS mc ON mc.CountryCode = c.CountryCode
JOIN Mountains AS m ON m.Id = mc.MountainId
JOIN Peaks AS p ON p.MountainId = m.Id
GROUP BY c.CountryName
ORDER BY HighestPeakElevation DESC,
LongestRiverLength DESC,
c.CountryName;
--Problem 18. *Highest Peak Name and Elevation by Country
--For each country, find the name and elevation of the highest peak, along with its mountain.
--When no peaks are available in some country, display elevation 0, "(no highest peak)" as peak name and "(no mountain)" as mountain name.
--When multiple peaks in some country have the same elevation, display all of them.
--Sort the results by country name alphabetically, then by highest peak name alphabetically. Limit only the first 5 rows.
SELECT TOP 5 k.CountryName,
ISNULL(k.[Highest Peak Name], '(no highest peak)'),
ISNULL(k.[Highest Peak Elevation], 0),
ISNULL(k.Mountain, '(no mountain)')
FROM
(
SELECT c.CountryName,
p.PeakName [Highest Peak Name],
MAX(p.Elevation) [Highest Peak Elevation],
m.MountainRange Mountain,
DENSE_RANK() OVER(PARTITION BY c.CountryName
ORDER BY MAX(p.Elevation) DESC) AS [Rank]
FROM Countries AS c
LEFT JOIN MountainsCountries AS mc ON mc.CountryCode = c.CountryCode
LEFT JOIN Mountains AS m ON m.Id = mc.MountainId
LEFT JOIN Peaks AS p ON p.MountainId = m.Id
GROUP BY c.CountryName,
p.PeakName,
m.MountainRange
) AS k
WHERE k.Rank = 1
ORDER BY k.CountryName,
k.[Highest Peak Name]; |
WITH attending_members AS (
SELECT count(workshop_invitations.member_id)
, workshop_invitations.member_id
FROM workshop_invitations
JOIN workshops ON workshops.id = workshop_invitations.workshop_id
WHERE workshops.date_and_time is not null
AND workshop_invitations.attending = 't'
GROUP BY member_id
)
, returning_members_count AS (
SELECT count(*)
FROM attending_members
WHERE count > 1
)
, attending_members_count AS (
SELECT count(*)
FROM attending_members
)
SELECT
returning_members_count.count as returning_members_count
, attending_members_count.count as attending_members_count
, (returning_members_count.count::DECIMAL / attending_members_count.count::DECIMAL) * 100.0 as percentage_returning
FROM
returning_members_count
, attending_members_count;
|
CREATE DATABASE `db_kgarth-o`; |
-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Hôte : db
-- Généré le : mar. 15 déc. 2020 à 15:20
-- Version du serveur : 5.7.32
-- Version de PHP : 7.4.11
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 */;
--
-- Base de données : `ppe3`
--
-- --------------------------------------------------------
--
-- Structure de la table `categorie`
--
CREATE TABLE `categorie` (
`Id_Categorie` int(11) NOT NULL,
`libelle` varchar(50) DEFAULT NULL,
`descriptif` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `categorie`
--
INSERT INTO `categorie` (`Id_Categorie`, `libelle`, `descriptif`) VALUES
(1, 'PC Portable', 'Mobile, léger, puissant'),
(2, 'Tour Gaming', 'Puissant, durable, Personnalisable'),
(3, 'Composants', 'Variés, Accessible');
-- --------------------------------------------------------
--
-- Structure de la table `client`
--
CREATE TABLE `client` (
`Id_Client` int(11) NOT NULL,
`prenom` varchar(50) DEFAULT NULL,
`nom` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`telephone` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `client`
--
INSERT INTO `client` (`Id_Client`, `prenom`, `nom`, `email`, `telephone`) VALUES
(3, 'test', 'TEST', 'test@test.com', '0606060606');
-- --------------------------------------------------------
--
-- Structure de la table `commande`
--
CREATE TABLE `commande` (
`Id_Commande` int(11) NOT NULL,
`date_commande` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`Id_Etat_Commande` int(11) NOT NULL,
`Id_Client` int(11) NOT NULL,
`Id_Personnel` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `commande`
--
INSERT INTO `commande` (`Id_Commande`, `date_commande`, `Id_Etat_Commande`, `Id_Client`, `Id_Personnel`) VALUES
(3, '2020-11-02 19:09:07', 1, 1, 1);
-- --------------------------------------------------------
--
-- Structure de la table `contenir`
--
CREATE TABLE `contenir` (
`Id_Commande` int(11) NOT NULL,
`Id_Produit` int(11) NOT NULL,
`quantite` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `contenir`
--
INSERT INTO `contenir` (`Id_Commande`, `Id_Produit`, `quantite`) VALUES
(1, 1, 9),
(1, 3, 2),
(1, 6, 8);
-- --------------------------------------------------------
--
-- Structure de la table `etat_commande`
--
CREATE TABLE `etat_commande` (
`Id_Etat_Commande` int(11) NOT NULL,
`libelle` varchar(50) DEFAULT NULL,
`descriptif` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `etat_commande`
--
INSERT INTO `etat_commande` (`Id_Etat_Commande`, `libelle`, `descriptif`) VALUES
(15, 'non-payé', ''),
(16, 'payé', ''),
(17, 'en cours de préparation', ''),
(18, 'préparé', ''),
(19, 'expédié', ''),
(20, 'livré', ''),
(21, 'terminé', '');
-- --------------------------------------------------------
--
-- Structure de la table `personnel`
--
CREATE TABLE `personnel` (
`Id_Personnel` int(11) NOT NULL,
`prenom` varchar(50) DEFAULT NULL,
`nom` varchar(50) DEFAULT NULL,
`pseudo` varchar(50) DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`telephone` varchar(50) DEFAULT NULL,
`email` varchar(180) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`Id_Profil` int(11) NOT NULL,
`roles` json NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `personnel`
--
INSERT INTO `personnel` (`Id_Personnel`, `prenom`, `nom`, `pseudo`, `password`, `telephone`, `email`, `Id_Profil`, `roles`) VALUES
(1, NULL, NULL, 'user', '$argon2id$v=19$m=65536,t=4,p=1$aYYjfqtF7u3mPlyHbd2hSw$ltwuuAzvN86+B+Jd0OQ5K781/CG4ymcHGGmZqp7DqEw', NULL, 'user@user.com', 2, '[\"ROLE_USER\"]'),
(2, NULL, NULL, 'root', '$argon2id$v=19$m=65536,t=4,p=1$oTlqBMSUQOX/+bSMGGfK5A$/t9wVJHpbAxQHx3Yx2kbtpBtaAoM/9fofXxa0F8GRBk', NULL, 'root@root.com', 1, '[\"ROLE_ADMIN\"]');
-- --------------------------------------------------------
--
-- Structure de la table `produit`
--
CREATE TABLE `produit` (
`Id_Produit` int(11) NOT NULL,
`libelle` varchar(50) DEFAULT NULL,
`description` text NOT NULL,
`tarif` decimal(19,4) DEFAULT NULL,
`stock` int(11) NOT NULL,
`note` decimal(15,2) DEFAULT NULL,
`lien_image` text,
`Id_Categorie` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `produit`
--
INSERT INTO `produit` (`Id_Produit`, `libelle`, `description`, `tarif`, `stock`, `note`, `lien_image`, `Id_Categorie`) VALUES
(15, 'Asus ROG Strix G (G531GT-HN574T)', '', '1099.9900', 10, '8.00', '', 1),
(16, 'test2', '', '40.0000', 50, '6.00', '', 3),
(17, 'test3', '', '50.0000', 20, '8.00', '', 3),
(18, 'test4', '', '25.0000', 25, '9.00', '', 3),
(19, 'test5', '', '400.0000', 50, '6.00', '', 2),
(20, 'test6', '', '1200.0000', 9, '8.00', '', 2),
(21, 'test7', '', '2000.0000', 5, '9.00', '', 2);
-- --------------------------------------------------------
--
-- Structure de la table `profil`
--
CREATE TABLE `profil` (
`Id_Profil` int(11) NOT NULL,
`libelle` varchar(50) DEFAULT NULL,
`descriptif` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `profil`
--
INSERT INTO `profil` (`Id_Profil`, `libelle`, `descriptif`) VALUES
(7, 'Administrateur', ''),
(8, 'Agent', '');
-- --------------------------------------------------------
--
-- Structure de la table `ref_produit`
--
CREATE TABLE `ref_produit` (
`Id_Ref_Produit` int(11) NOT NULL,
`Ref_Produit` varchar(50) DEFAULT NULL,
`Id_Produit` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Index pour les tables déchargées
--
--
-- Index pour la table `categorie`
--
ALTER TABLE `categorie`
ADD PRIMARY KEY (`Id_Categorie`);
--
-- Index pour la table `client`
--
ALTER TABLE `client`
ADD PRIMARY KEY (`Id_Client`);
--
-- Index pour la table `commande`
--
ALTER TABLE `commande`
ADD PRIMARY KEY (`Id_Commande`),
ADD KEY `Id_Etat_Commande` (`Id_Etat_Commande`),
ADD KEY `Id_Client` (`Id_Client`),
ADD KEY `Id_Personnel` (`Id_Personnel`);
--
-- Index pour la table `contenir`
--
ALTER TABLE `contenir`
ADD PRIMARY KEY (`Id_Produit`,`Id_Commande`),
ADD KEY `Id_Commande` (`Id_Commande`);
--
-- Index pour la table `etat_commande`
--
ALTER TABLE `etat_commande`
ADD PRIMARY KEY (`Id_Etat_Commande`);
--
-- Index pour la table `personnel`
--
ALTER TABLE `personnel`
ADD PRIMARY KEY (`Id_Personnel`),
ADD KEY `Id_Profil` (`Id_Profil`);
--
-- Index pour la table `produit`
--
ALTER TABLE `produit`
ADD PRIMARY KEY (`Id_Produit`),
ADD KEY `Id_Categorie` (`Id_Categorie`);
--
-- Index pour la table `profil`
--
ALTER TABLE `profil`
ADD PRIMARY KEY (`Id_Profil`);
--
-- Index pour la table `ref_produit`
--
ALTER TABLE `ref_produit`
ADD PRIMARY KEY (`Id_Ref_Produit`),
ADD KEY `Id_Produit` (`Id_Produit`);
--
-- AUTO_INCREMENT pour les tables déchargées
--
--
-- AUTO_INCREMENT pour la table `categorie`
--
ALTER TABLE `categorie`
MODIFY `Id_Categorie` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT pour la table `client`
--
ALTER TABLE `client`
MODIFY `Id_Client` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT pour la table `commande`
--
ALTER TABLE `commande`
MODIFY `Id_Commande` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT pour la table `etat_commande`
--
ALTER TABLE `etat_commande`
MODIFY `Id_Etat_Commande` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
--
-- AUTO_INCREMENT pour la table `personnel`
--
ALTER TABLE `personnel`
MODIFY `Id_Personnel` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT pour la table `produit`
--
ALTER TABLE `produit`
MODIFY `Id_Produit` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
--
-- AUTO_INCREMENT pour la table `profil`
--
ALTER TABLE `profil`
MODIFY `Id_Profil` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT pour la table `ref_produit`
--
ALTER TABLE `ref_produit`
MODIFY `Id_Ref_Produit` int(11) NOT NULL AUTO_INCREMENT;
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 */;
|
CREATE TABLE students(
id INTEGER PRIMARY KEY,
eid TEXT UNIQUE,
pass TEXT,
firstName TEXT,
lastName TEXT
)
|
SELECT DISTINCT
type,
Laptop.model,
speed
FROM Laptop
INNER JOIN Product
ON Laptop.model = Product.model
WHERE speed < ALL (SELECT
speed
FROM PC) |
SET STATISTICS IO ON;
WITH
AGG(
PART,
WRKO,
BTID,
DEPT,
RESC,
RDAT,
PDAT,
SEQ,
QTY_CONSUME,
QTY_PRODUCE,
WGT_CONSUME,
WGT_PRODUCE,
UOM
) AS (
SELECT
PART,
WRKO,
BTID,
DEPT,
RESC,
RDAT,
PDAT,
SEQ,
SUM(QTY_CONSUME) QTY_CONSUME,
SUM(QTY_PRODUCE) QTY_PRODUCE,
SUM(WGT_CONSUME) WGT_CONSUME,
SUM(WGT_PRODUCE) WGT_PRODUCE,
UOM
FROM
(
-----RPRM materials consumed--------------
SELECT
UIPART PART,
UIJOB# WRKO,
UIBTID BTID,
UIDEPT DEPT,
UIRESC RESC,
NWRDAT RDAT,
CAST(FORMAT(NWFUT9/10,'0000-00-00') AS DATE) PDAT,
UISEQ# SEQ,
---note:scrap batches included in consumption
SUM(
UITQTY *
CASE UIRQBY WHEN 'B' THEN -1 ELSE 1 END
) QTY_CONSUME,
0 QTY_PRODUCE,
SUM(
UITQTY *
CASE UIRQBY WHEN 'B' THEN -1 ELSE 1 END *
COALESCE(AVNWHT, AWNWHT) *
CASE COALESCE(AVNWUN, AWNWUN) WHEN 'KG' THEN 2.2046 ELSE 1 END
) WGT_CONSUME,
0 WGT_PRODUCE,
CASE COALESCE(AVNWUN, AWNWUN) WHEN 'KG' THEN 'LB' ELSE COALESCE(AVNWUN, AWNWUN) END UOM
FROM
LGDAT.RPRM
INNER JOIN LGDAT.RPRH ON
NWBTID = UIBTID
LEFT OUTER JOIN LGDAT.STKMM ON
AVPART = UIMTLP
LEFT OUTER JOIN LGDAT.STKMP ON
AWPART = UIMTLP
WHERE
NWFSYY = 17 AND
NWFSPP = 3 AND
COALESCE(AWMAJG, AVMAJG) = '710'
GROUP BY
UIPART,
UIJOB#,
UIBTID,
UIDEPT,
UIRESC,
NWRDAT,
CAST(FORMAT(NWFUT9/10,'0000-00-00') AS DATE),
UISEQ#,
CASE COALESCE(AVNWUN, AWNWUN) WHEN 'KG' THEN 'LB' ELSE COALESCE(AVNWUN, AWNWUN) END
UNION ALL
--------RPRP materials produced------------------
SELECT
OAPART PART,
OAJOB# WRKO,
OABTID BTID,
OADEPT DEPT,
OARESC RESC,
NWRDAT RDAT,
CAST(FORMAT(NWFUT9/10,'0000-00-00') AS DATE) PDAT,
OASEQ# SEQ,
0 QTY_CONSUME,
---note: scrap included in output
SUM(OAQTYG + OAQTYS) QTY_PRODUCE,
0 WGT_CONSUME,
SUM(
(OAQTYG + OAQTYS) *
COALESCE(AVNWHT, AWNWHT) *
CASE COALESCE(AVNWUN, AWNWUN) WHEN 'KG' THEN 2.2046 ELSE 1 END
) WGT_PRODUCE,
CASE COALESCE(AVNWUN, AWNWUN) WHEN 'KG' THEN 'LB' ELSE COALESCE(AVNWUN, AWNWUN) END UOM
FROM
LGDAT.RPRR
INNER JOIN LGDAT.RPRH ON
NWBTID = OABTID
LEFT OUTER JOIN LGDAT.STKMM ON
AVPART = OAPART
LEFT OUTER JOIN LGDAT.STKMP ON
AWPART = OAPART
WHERE
NWFSYY = 17 AND
NWFSPP = 3 AND
OASEQ# = 10
GROUP BY
OAPART,
OAJOB#,
OABTID,
OADEPT,
OARESC,
NWRDAT,
CAST(FORMAT(NWFUT9/10,'0000-00-00') AS DATE),
OASEQ#,
CASE COALESCE(AVNWUN, AWNWUN) WHEN 'KG' THEN 'LB' ELSE COALESCE(AVNWUN, AWNWUN) END
) X
GROUP BY
PART,
WRKO,
BTID,
DEPT,
RESC,
RDAT,
PDAT,
SEQ,
UOM
)
SELECT
DEPT, UOM, SUM(WGT_CONSUME), SUM(WGT_PRODUCE)
FROM
AGG
GROUP BY
DEPT, UOM
OPTION (MAXDOP 8, RECOMPILE) |
CREATE TABLE Categoria_Articulo(
idCategoriaPublicacion int NOT NULL,
PRIMARY KEY (idCategoriaPublicacion),
FOREIGN KEY (idCategoriaPublicacion) REFERENCES categoria(idCategoriaPublicacion)
) |
-- phpMyAdmin SQL Dump
-- version 4.2.12deb2+deb8u1build0.15.04.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Sep 08, 2016 at 09:40 AM
-- Server version: 5.6.28-0ubuntu0.15.04.1
-- PHP Version: 5.6.4-4ubuntu6.4
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: `traffic`
--
-- --------------------------------------------------------
--
-- Table structure for table `traffic_camera_info`
--
CREATE TABLE IF NOT EXISTS `traffic_camera_info` (
`id` int(11) NOT NULL,
`camera` varchar(50) DEFAULT NULL,
`traffic` int(11),
`timestamp` datetime DEFAULT NULL,
`latitude` double DEFAULT NULL,
`longitude` double DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1024 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `traffic_camera_info`
--
INSERT INTO `traffic_camera_info` (`id`, `camera`, `traffic`, `timestamp`, `latitude`, `longitude`) VALUES
(1, 'GP::GP CCTV N1 004', NULL, NULL, -25.878076, 28.16885545),
(2, 'GP::GP CCTV N1 4002', NULL, NULL, -25.878538, 28.16875219),
(3, 'GP::GP CCTV N1 045', NULL, NULL, -26.045196, 28.098013),
(4, 'GP::GP CCTV N1 048', NULL, NULL, -26.047132, 28.096255),
(5, 'GP::GP CCTV M1 702B', NULL, NULL, -26.262284, 27.98553586),
(6, 'GP::GP CCTV N1 049', NULL, NULL, -26.049686, 28.09459166),
(7, 'GP::GP CCTV N3 320', NULL, NULL, -26.213173, 28.13574492),
(8, 'GP::GP CCTV N1 613', NULL, NULL, -26.071756, 27.97360002),
(9, 'GP::GP CCTV N1 637', NULL, NULL, -26.266432, 27.95165687),
(10, 'GP::GP CCTV N1 029', NULL, NULL, -25.982622, 28.12579722),
(11, 'GP::GP CCTV N1 2101', NULL, NULL, -25.954627, 28.13423752),
(12, 'GP::GP CCTV N1 603', NULL, NULL, -26.039578, 28.07002),
(13, 'GP::GP CCTV N1 019', NULL, NULL, -25.945072, 28.13778611),
(14, 'GP::GP CCTV N1 011', NULL, NULL, -25.907868, 28.158668),
(15, 'GP::GP CCTV N1 028', NULL, NULL, -25.980886, 28.1263),
(16, 'GP::GP CCTV N1 023', NULL, NULL, -25.961838, 28.132192),
(17, 'GP::GP CCTV N1 007', NULL, NULL, -25.89341, 28.165203),
(18, 'GP::GP CCTV N1 202', NULL, NULL, -25.756371, 28.275025),
(19, 'GP::GP CCTV N1 012', NULL, NULL, -25.91097, 28.156613),
(20, 'GP::GP CCTV N1 017', NULL, NULL, -25.935641, 28.14196388),
(21, 'GP::GP CCTV N1 008', NULL, NULL, -25.897489, 28.163865),
(22, 'GP::GP CCTV N1 015', NULL, NULL, -25.92365, 28.14860277),
(23, 'GP::GP CCTV N1 201A', NULL, NULL, -25.751722, 28.273803),
(24, 'GP::GP CCTV N1 041', NULL, NULL, -26.036097, 28.10779722),
(25, 'GP::GP CCTV N1 042', NULL, NULL, -26.039777, 28.106258),
(26, 'GP::GP CCTV N1 604', NULL, NULL, -26.038305, 28.06136325),
(27, 'GP::GP CCTV N1 208', NULL, NULL, -25.809579, 28.259204),
(28, 'GP::GP CCTV N1 024', NULL, NULL, -25.968722, 28.13009722),
(29, 'GP::GP CCTV N1 2001', NULL, NULL, -25.87235, 28.18045),
(30, 'GP::GP CCTV N1 003', NULL, NULL, -25.875813, 28.17296944),
(31, 'GP::GP CCTV N1 034', NULL, NULL, -26.008436, 28.11948333),
(32, 'GP::GP CCTV N4 101', NULL, NULL, -25.739811, 28.26507222),
(33, 'GP::GP CCTV N1 002', NULL, NULL, -25.872613, 28.18029642),
(34, 'GP::GP CCTV N1 036', NULL, NULL, -26.017139, 28.117787),
(35, 'GP::GP CCTV N1 207', NULL, NULL, -25.799536, 28.262452),
(36, 'GP::GP CCTV N1 1602', NULL, NULL, -25.932255, 28.144696),
(37, 'GP::GP CCTV N1 005', NULL, NULL, -25.882214, 28.167981),
(38, 'GP::GP CCTV N1 203', NULL, NULL, -25.766327, 28.275314),
(39, 'GP::GP CCTV N1 215', NULL, NULL, -25.862976, 28.20214),
(40, 'GP::GP CCTV N1 205', NULL, NULL, -25.779009, 28.272226),
(41, 'GP::GP CCTV N1 638', NULL, NULL, -26.276218, 27.94702336),
(42, 'GP::GP CCTV N1 637a', NULL, NULL, -26.272824, 27.94750213),
(43, 'GP::GP CCTV N1 607', NULL, NULL, -26.036486, 28.02016988),
(44, 'GP::GP CCTV N1 608A', NULL, NULL, -26.040741, 28.00818577),
(45, 'GP::GP CCTV N1 622', NULL, NULL, -26.151465, 27.92733728),
(46, 'GP::GP CCTV N1 621', NULL, NULL, -26.138719, 27.93371692),
(47, 'GP::GP CCTV N1 620A', NULL, NULL, -26.135146, 27.9359807),
(48, 'GP::GP CCTV N1 627A', NULL, NULL, -26.190453, 27.94843688),
(49, 'GP::GP CCTV N1 630A', NULL, NULL, -26.218297, 27.95997843),
(50, 'GP::GP CCTV N1 631', NULL, NULL, -26.222925, 27.96132892),
(51, 'GP::GP CCTV 619', NULL, NULL, -26.123476, 27.94413864),
(52, 'GP::GP CCTV 620', NULL, NULL, -26.12904, 27.93999195),
(53, 'GP::GP CCTV 615', NULL, NULL, -26.094718, 27.96694546),
(54, 'GP::GP CCTV N1 039', NULL, NULL, -26.026947, 28.110724),
(55, 'GP::GP CCTV N1 040', NULL, NULL, -26.03259, 28.10867),
(56, 'GP::GP CCTV N1 050', NULL, NULL, -26.048022, 28.097598),
(57, 'GP::GP CCTV N1 030', NULL, NULL, -25.986712, 28.124607),
(58, 'GP::GP CCTV N1 210', NULL, NULL, -25.829534, 28.244115),
(59, 'GP::GP CCTV N1 213', NULL, NULL, -25.85496, 28.225623),
(60, 'GP::GP CCTV N1 035', NULL, NULL, -26.013347, 28.11724166),
(61, 'GP::GP CCTV N1 605', NULL, NULL, -26.037955, 28.05037021),
(62, 'GP::GP CCTV N1 1601', NULL, NULL, -25.928712, 28.145518),
(63, 'GP::GP CCTV N1 009', NULL, NULL, -25.901145, 28.162345),
(64, 'GP::GP CCTV N1 010', NULL, NULL, -25.90513, 28.160331),
(65, 'GP::GP CCTV N1 212', NULL, NULL, -25.842369, 28.231353),
(66, 'GP::GP CCTV N1 209', NULL, NULL, -25.819769, 28.253443),
(67, 'GP::GP CCTV N1 4001', NULL, NULL, -25.877881, 28.169322),
(68, 'GP::GP CCTV N1 628', NULL, NULL, -26.198651, 27.95262381),
(69, 'GP::GP CCTV N1 614', NULL, NULL, -26.081676, 27.9700756),
(70, 'GP::GP CCTV N1 613A', NULL, NULL, -26.074313, 27.97244668),
(71, 'GP::GP CCTV N1013', NULL, NULL, -25.915989, 28.15323963),
(72, 'GP::GP CCTV N1 614A', NULL, NULL, -26.086484, 27.96886593),
(73, 'GP::GP CCTV N1 612', NULL, NULL, -26.065361, 27.97872975),
(74, 'GP::GP CCTV N1 Pilot 38', NULL, NULL, -26.023421, 28.11190545),
(75, 'GP::GP CCTV N1 602', NULL, NULL, -26.040342, 28.07350292),
(76, 'GP::GP CCTV N1 632', NULL, NULL, -26.231659, 27.96083807),
(77, 'GP::GP CCTV N1 601A', NULL, NULL, -26.041725, 28.08246955),
(78, 'GP::GP CCTV N1 631A', NULL, NULL, -26.22838, 27.96151667),
(79, 'GP::GP CCTV N1 610', NULL, NULL, -26.048311, 27.99917221),
(80, 'GP::GP CCTV N1 611', NULL, NULL, -26.053711, 27.99246132),
(81, 'GP::GP CCTV N1 032', NULL, NULL, -25.99913, 28.12150555),
(82, 'GP::GP CCTV N1 031', NULL, NULL, -25.99243, 28.12278611),
(83, 'GP::GP CCTV N1 021', NULL, NULL, -25.954422, 28.13466),
(84, 'GP::GP CCTV N1 006', NULL, NULL, -25.887924, 28.166601),
(85, 'GP::GP CCTV N1 206', NULL, NULL, -25.79079, 28.268848),
(86, 'GP::GP CCTV N1 025', NULL, NULL, -25.978117, 28.127168),
(87, 'GP::GP CCTV N1 216', NULL, NULL, -25.867625, 28.192645),
(88, 'GP::GP CCTV N1 201', NULL, NULL, -25.74499, 28.267973),
(89, 'GP::GP CCTV N1 020', NULL, NULL, -25.949272, 28.13623055),
(90, 'GP::GP CCTV N1 1001', NULL, NULL, -25.904618, 28.16033273),
(91, 'GP::GP CCTV N1 204', NULL, NULL, -25.769395, 28.274575),
(92, 'GP::GP CCTV N1 601', NULL, NULL, -26.042698, 28.087743),
(93, 'GP::GP CCTV N1 2701', NULL, NULL, -25.980276, 28.12635585),
(94, 'GP::GP CCTV N1 022', NULL, NULL, -25.957727, 28.133471),
(95, 'GP::GP CCTV N1 044', NULL, NULL, -26.043526, 28.101629),
(96, 'GP::GP CCTV N1 016', NULL, NULL, -25.928455, 28.145725),
(97, 'GP::GP CCTV N1 214', NULL, NULL, -25.859883, 28.218509),
(98, 'GP::GP CCTV N1 037', NULL, NULL, -26.019527, 28.11468888),
(99, 'GP::GP CCTV N1 027', NULL, NULL, -25.980236, 28.12617614),
(100, 'GP::GP CCTV N1 043', NULL, NULL, -26.041769, 28.10416111),
(101, 'GP::GP CCTV N1 636', NULL, NULL, -26.2636, 27.9567638),
(102, 'GP::GP CCTV N1 634', NULL, NULL, -26.256745, 27.96331644),
(103, 'GP::GP CCTV N1 634A', NULL, NULL, -26.253144, 27.96429678),
(104, 'GP::GP CCTV N1 211', NULL, NULL, -25.834016, 28.23917359),
(105, 'GP::GP CCTV N12 405', NULL, NULL, -26.162918, 28.16681161),
(106, 'GP::GP CCTV N12 407', NULL, NULL, -26.165932, 28.18757057),
(107, 'GP::GP CCTV N12 408', NULL, NULL, -26.170715, 28.19226443),
(108, 'GP::GP CCTV N12 409', NULL, NULL, -26.175888, 28.19850593),
(109, 'GP::GP CCTV N12 414', NULL, NULL, -26.172601, 28.25738176),
(110, 'GP::GP CCTV N12 415', NULL, NULL, -26.173097, 28.27234983),
(111, 'GP::GP CCTV N12 411', NULL, NULL, -26.179716, 28.2151021),
(112, 'GP::GP CCTV N12 411B', NULL, NULL, -26.175542, 28.2257089),
(113, 'GP::GP CCTV N12 702', NULL, NULL, -26.262683, 27.97614946),
(114, 'GP::GP CCTV N12 712', NULL, NULL, -26.267108, 28.07146713),
(115, 'GP::GP CCTV N12 415A', NULL, NULL, -26.173825, 28.28015103),
(116, 'GP::GP CCTV N12 422', NULL, NULL, -26.175515, 28.33381131),
(117, 'GP::GP CCTV N12 421', NULL, NULL, -26.177357, 28.32690462),
(118, 'GP::GP CCTV N12 707A', NULL, NULL, -26.26636, 28.02487984),
(119, 'GP::GP CCTV 708A', NULL, NULL, -26.267826, 28.03394973),
(120, 'GP::GP CCTV N12 707B', NULL, NULL, -26.265953, 28.02870199),
(121, 'GP::GP CCTV N12 416A', NULL, NULL, -26.175458, 28.28947842),
(122, 'GP::GP CCTV N12 417A', NULL, NULL, -26.180564, 28.30086976),
(123, 'GP::GP CCTV N12 423', NULL, NULL, -26.172467, 28.34442481),
(124, 'GP::GP CCTV N12 424', NULL, NULL, -26.166628, 28.35571154),
(125, 'GP::GP CCTV N12 425', NULL, NULL, -26.162901, 28.36204558),
(126, 'GP::GP CCTV N12 426', NULL, NULL, -26.164811, 28.36909577),
(127, 'GP::GP CCTV N12 427', NULL, NULL, -26.167061, 28.37800204),
(128, 'GP::GP CCTV N12 429', NULL, NULL, -26.167295, 28.38976353),
(129, 'GP::GP CCTV N12 430', NULL, NULL, -26.16666, 28.39730054),
(130, 'GP::GP CCTV N12 708', NULL, NULL, -26.26638, 28.03020402),
(131, 'GP::GP CCTV N12 420A', NULL, NULL, -26.180046, 28.32106143),
(132, 'GP::GP CCTV N12 417', NULL, NULL, -26.179721, 28.29832568),
(133, 'GP::GP CCTV N12 716', NULL, NULL, -26.25821, 28.11790287),
(134, 'GP::GP CCTV N12 410', NULL, NULL, -26.179338, 28.20499822),
(135, 'GP::GP CCTV N12 703', NULL, NULL, -26.261885, 27.99322575),
(136, 'GP::GP CCTV N12 715A', NULL, NULL, -26.259618, 28.11233729),
(137, 'GP::GP CCTV N12 428', NULL, NULL, -26.167389, 28.3849503),
(138, 'GP::GP CCTV N12 717', NULL, NULL, -26.254268, 28.12109604),
(139, 'GP::GP CCTV N12 718', NULL, NULL, -26.250433, 28.12199592),
(140, 'GP::GP CCTV N12 711', NULL, NULL, -26.268884, 28.0608496),
(141, 'GP::GP CCTV N12 711A', NULL, NULL, -26.268621, 28.06587874),
(142, 'GP::GP CCTV 709A', NULL, NULL, -26.270962, 28.04545238),
(143, 'GP::GP CCTV 709', NULL, NULL, -26.270663, 28.04017245),
(144, 'GP::GP CCTV N12 402', NULL, NULL, -26.166722, 28.14162701),
(145, 'GP::GP CCTV N12 403', NULL, NULL, -26.165206, 28.14586624),
(146, 'GP::GP CCTV N12 404', NULL, NULL, -26.163614, 28.15649583),
(147, 'GP::GP CCTV N12 406', NULL, NULL, -26.164864, 28.18065583),
(148, 'GP::GP CCTV N12 408A', NULL, NULL, -26.172497, 28.19341376),
(149, 'GP::GP CCTV N12 416', NULL, NULL, -26.174522, 28.28686594),
(150, 'GP::GP CCTV N12 418', NULL, NULL, -26.180615, 28.3041796),
(151, 'GP::GP CCTV N12 419', NULL, NULL, -26.181567, 28.31047207),
(152, 'GP::GP CCTV N12 715', NULL, NULL, -26.260979, 28.10682803),
(153, 'GP::GP CCTV N12 720', NULL, NULL, -26.24149, 28.12602594),
(154, 'GP::GP CCTV N12 719', NULL, NULL, -26.244105, 28.12384396),
(155, 'GP::GP CCTV N1 633A', NULL, NULL, -26.257637, 27.96494856),
(156, 'GP::GP CCTV N12 635', NULL, NULL, -26.258792, 27.96512559),
(157, 'GP::GP CCTV N12 702A', NULL, NULL, -26.263031, 27.98324659),
(158, 'GP::GP CCTV N17 506', NULL, NULL, -26.257498, 28.178825),
(159, 'GP::GP CCTV N17 504', NULL, NULL, -26.248281, 28.164115),
(160, 'GP::GP CCTV N17 507', NULL, NULL, -26.255287, 28.188435),
(161, 'GP::GP CCTV N17 510', NULL, NULL, -26.251081, 28.244886),
(162, 'GP::GP CCTV N17 501', NULL, NULL, -26.246399, 28.133003),
(163, 'GP::GP CCTV N17 509', NULL, NULL, -26.251237, 28.220893),
(164, 'GP::GP CCTV N17 508', NULL, NULL, -26.251151, 28.211898),
(165, 'GP::GP CCTV N17 503', NULL, NULL, -26.248589, 28.154343),
(166, 'GP::GP CCTV N17 505', NULL, NULL, -26.256596, 28.172705),
(167, 'GP::GP CCTV N17 502', NULL, NULL, -26.25184, 28.141369),
(168, 'GP::GP CCTV N17 551', NULL, NULL, -26.244935, 28.12782973),
(169, 'GP::GP CCTV N1 052', NULL, NULL, -26.050905, 28.10105),
(170, 'GP::GP CCTV N3 312', NULL, NULL, -26.170322, 28.131867),
(171, 'GP::GP CCTV N3 322', NULL, NULL, -26.224446, 28.12667503),
(172, 'GP::GP CCTV N3 308', NULL, NULL, -26.137617, 28.132419),
(173, 'GP::GP CCTV N3 304A', NULL, NULL, -26.112279, 28.13119187),
(174, 'GP::GP CCTV N3 329', NULL, NULL, -26.261996, 28.15126),
(175, 'GP::GP CCTV N3 317', NULL, NULL, -26.20044, 28.13341274),
(176, 'GP::GP CCTV N3 325', NULL, NULL, -26.24236, 28.13159421),
(177, 'GP::GP CCTV N3 303', NULL, NULL, -26.094238, 28.117351),
(178, 'GP::GP CCTV N1 051', NULL, NULL, -26.048885, 28.098534),
(179, 'GP::GP CCTV N3 304', NULL, NULL, -26.104604, 28.124651),
(180, 'GP::GP CCTV N3 328', NULL, NULL, -26.252774, 28.150135),
(181, 'GP::GP CCTV N3 311', NULL, NULL, -26.168547, 28.133198),
(182, 'GP::GP CCTV N3 327', NULL, NULL, -26.249964, 28.148464),
(183, 'GP::GP CCTV N3 331', NULL, NULL, -26.279694, 28.149672),
(184, 'GP::GP CCTV N1 046', NULL, NULL, -26.045808, 28.094443),
(185, 'GP::GP CCTV N3 307', NULL, NULL, -26.127295, 28.134987),
(186, 'GP::GP CCTV N3 309', NULL, NULL, -26.149368, 28.13104972),
(187, 'GP::GP CCTV N3 314', NULL, NULL, -26.179843, 28.133755),
(188, 'GP::GP CCTV N3 313', NULL, NULL, -26.176098, 28.131095),
(189, 'GP::GP CCTV N3 323', NULL, NULL, -26.233894, 28.1255123),
(190, 'GP::GP CCTV N3 306', NULL, NULL, -26.124237, 28.136552),
(191, 'GP::GP CCTV N3 305', NULL, NULL, -26.114015, 28.132258),
(192, 'GP::GP CCTV N3 332', NULL, NULL, -26.291906, 28.154924),
(193, 'GP::GP CCTV N3 330', NULL, NULL, -26.273422, 28.149058),
(194, 'GP::GP CCTV N3 310', NULL, NULL, -26.158908, 28.133535),
(195, 'GP::GP CCTV N3 315', NULL, NULL, -26.18911, 28.134562),
(196, 'GP::GP CCTV N3 300A', NULL, NULL, -26.059225, 28.106353),
(197, 'GP::GP CCTV N3 301', NULL, NULL, -26.068027, 28.110675),
(198, 'GP::GP CCTV N3 326', NULL, NULL, -26.247566, 28.140198),
(199, 'GP::GP CCTV N3 302', NULL, NULL, -26.082243, 28.11492),
(200, 'GP::GP CCTV N1 047', NULL, NULL, -26.04513, 28.09293333),
(201, 'GP::GP CCTV N3 316', NULL, NULL, -26.19452, 28.13187986),
(202, 'GP::GP CCTV N3 318', NULL, NULL, -26.203053, 28.13508242),
(203, 'GP::GP CCTV N3 319', NULL, NULL, -26.209493, 28.13641414),
(204, 'GP::GP CCTV N3 321', NULL, NULL, -26.215924, 28.13199788),
(205, 'GP::GP CCTV N4 105', NULL, NULL, -25.746022, 28.291858),
(206, 'GP::GP CCTV N4 103', NULL, NULL, -25.741236, 28.2807),
(207, 'GP::GP CCTV N4 110', NULL, NULL, -25.756297, 28.343456),
(208, 'GP::GP CCTV N4 102', NULL, NULL, -25.740656, 28.272817),
(209, 'GP::GP CCTV N4 104', NULL, NULL, -25.741422, 28.286264),
(210, 'GP::GP CCTV N4 114', NULL, NULL, -25.769756, 28.412022),
(211, 'GP::GP CCTV N4 107', NULL, NULL, -25.753124, 28.315866),
(212, 'GP::GP CCTV N4 106', NULL, NULL, -25.753294, 28.305075),
(213, 'GP::GP CCTV N4 108', NULL, NULL, -25.752633, 28.325151),
(214, 'GP::GP CCTV N4 113', NULL, NULL, -25.766422, 28.394075),
(215, 'GP::GP CCTV N4 109', NULL, NULL, -25.751994, 28.334189),
(216, 'GP::GP CCTV N4 111', NULL, NULL, -25.760106, 28.362158),
(217, 'GP::GP CCTV N4 112', NULL, NULL, -25.762533, 28.376481),
(218, 'GP::GP CCTV R21 820', NULL, NULL, -26.13672, 28.222721),
(219, 'GP::GP CCTV R21', NULL, NULL, -25.921089, 28.26168134),
(220, 'GP::GP CCTV R21 817', NULL, NULL, -26.109917, 28.238997),
(221, 'GP::GP CCTV R21 808B', NULL, NULL, -25.989909, 28.251334),
(222, 'GP::GP CCTV R21 810', NULL, NULL, -26.018412, 28.260039),
(223, 'GP::GP CCTV R21 818', NULL, NULL, -26.124331, 28.235694),
(224, 'GP::CCTV 822', NULL, NULL, -26.154308, 28.22302132),
(225, 'GP::CCTV 814', NULL, NULL, -26.092194, 28.26801672),
(226, 'GP::CCTV 811', NULL, NULL, -26.03072, 28.26569259),
(227, 'GP::CCTV 809', NULL, NULL, -26.00419, 28.25146347),
(228, 'GP::CCTV 805', NULL, NULL, -25.904731, 28.25547203),
(229, 'GP::GP CCTV R21 804A', NULL, NULL, -25.873173, 28.25433075),
(230, 'GP::CCTV 801', NULL, NULL, -25.814595, 28.23482304),
(231, 'GP::GP CCTV R21 813', NULL, NULL, -26.078806, 28.2722),
(232, 'GP::GP CCTV R21 816', NULL, NULL, -26.102583, 28.2495),
(233, 'GP::GP CCTV R21 811B', NULL, NULL, -26.051369, 28.280881),
(234, 'GP::GP CCTV R21 802', NULL, NULL, -25.840831, 28.249377),
(235, 'GP::GP CCTV R21 815', NULL, NULL, -26.100017, 28.257957),
(236, 'GP::GP CCTV R21 812', NULL, NULL, -26.063675, 28.27769011),
(237, 'GP::GP CCTV R21 823', NULL, NULL, -26.162051, 28.22694003),
(238, 'GP::GP CCTV R21 807A', NULL, NULL, -25.963188, 28.25520113),
(239, 'GP::GP CCTV R21 801A', NULL, NULL, -25.821856, 28.23973819),
(240, 'GP::GP CCTV R21 821', NULL, NULL, -26.144592, 28.21966722),
(241, 'GP::GP CCTV R21 821A', NULL, NULL, -26.145348, 28.21965917),
(242, 'GP::GP CCTV R21 804', NULL, NULL, -25.864822, 28.253597),
(243, 'GP::GP CCTV R21 804B', NULL, NULL, -25.887951, 28.25522),
(244, 'GP::GP CCTV R21 808', NULL, NULL, -25.975577, 28.252799),
(245, 'GP::GP CCTV R21 807', NULL, NULL, -25.950778, 28.257447),
(246, 'GP::GP CCTV R21 819', NULL, NULL, -26.130347, 28.227511),
(247, 'GP::GP CCTV R21 803', NULL, NULL, -25.849405, 28.25132936),
(248, 'GP::GP CCTV R21 805A', NULL, NULL, -25.910298, 28.2577452),
(249, 'GP::GP CCTV R21 806A', NULL, NULL, -25.943148, 28.25919494),
(250, 'GP::GP CCTV R21 812B', NULL, NULL, -26.074094, 28.27269583),
(251, 'GP::GP CCTV R21 825', NULL, NULL, -26.168589, 28.2301104),
(252, 'GP::CCTV 901', NULL, NULL, -26.129161, 28.21341365),
(253, 'GP::CCTV 903', NULL, NULL, -26.13773, 28.19570973),
(254, 'GP::CCTV 902', NULL, NULL, -26.13003, 28.20676982),
(255, 'GP::CCTV 904', NULL, NULL, -26.14601, 28.1814377),
(256, 'GP::CCTV 905', NULL, NULL, -26.151218, 28.17036285),
(257, 'GP::CCTV 906', NULL, NULL, -26.156464, 28.16307529),
(258, 'GP::GP CCTV N1 627', NULL, NULL, -26.185677, 27.94589281),
(259, 'GP::GP CCTV N1 635A', NULL, NULL, -26.260989, 27.96236157),
(260, 'GP::GP CCTV N1 633', NULL, NULL, -26.250022, 27.96470984),
(261, 'GP::GP CCTV N12 420', NULL, NULL, -26.180883, 28.31470325),
(262, 'GP::GP CCTV N1 608', NULL, NULL, -26.03839, 28.0131787),
(263, 'GP::GP CCTV N12 701', NULL, NULL, -26.261529, 27.96842738),
(264, 'GP::GP CCTV N12 401', NULL, NULL, -26.16743, 28.13912048),
(265, 'GP::GP CCTV N3 324', NULL, NULL, -26.240192, 28.12892809),
(266, 'GP::GP CCTV N12 412', NULL, NULL, -26.172846, 28.23233798),
(267, 'GP::GP CCTV N1 634B', NULL, NULL, -26.257164, 27.96167358),
(268, 'GP::GP CCTV N12 714', NULL, NULL, -26.264343, 28.09597447),
(269, 'GP::GP CCTV N1 604A', NULL, NULL, -26.037976, 28.05779188),
(270, 'GP::GP CCTV N12 413', NULL, NULL, -26.172027, 28.24145212),
(271, 'KZN::KZN CCTV N2/N3 0022A', NULL, NULL, -29.839819, 30.958392),
(272, 'KZN::KZN CCTV N3 227', NULL, NULL, -29.825247, 30.871631),
(273, 'KZN::KZN CCTV N2 025 Fixed', NULL, NULL, -29.825846, 30.96700295),
(274, 'KZN::KZN CCTV N2 033', NULL, NULL, -29.757009, 31.0168451),
(275, 'KZN::KZN CCTV N2 001', NULL, NULL, -29.969728, 30.9419),
(276, 'KZN::KZN CCTV N2 016', NULL, NULL, -29.884325, 30.944911),
(277, 'KZN::KZN CCTV N2 004', NULL, NULL, -29.953059, 30.94756364),
(278, 'KZN::KZN CCTV N2 034', NULL, NULL, -29.757211, 31.016789),
(279, 'KZN::KZN CCTV N2 032', NULL, NULL, -29.765561, 31.004914),
(280, 'KZN::KZN CCTV N2 051', NULL, NULL, -29.585089, 31.142644),
(281, 'KZN::KZN CCTV N2 012', NULL, NULL, -29.902678, 30.952725),
(282, 'KZN::KZN CCTV N2 010', NULL, NULL, -29.921256, 30.948508),
(283, 'KZN::KZN CCTV N2 029', NULL, NULL, -29.789439, 30.995889),
(284, 'KZN::KZN CCTV N2 048', NULL, NULL, -29.6335, 31.120317),
(285, 'KZN::KZN CCTV N2 036', NULL, NULL, -29.74273, 31.04265198),
(286, 'KZN::KZN CCTV N2 044', NULL, NULL, -29.669353, 31.097783),
(287, 'KZN::KZN CCTV N2 024', NULL, NULL, -29.830314, 30.961317),
(288, 'KZN::KZN CCTV N2 019', NULL, NULL, -29.864122, 30.950919),
(289, 'KZN::KZN CCTV N2 009', NULL, NULL, -29.929694, 30.947994),
(290, 'KZN::KZN CCTV N2 020', NULL, NULL, -29.851578, 30.951669),
(291, 'KZN::KZN CCTV N2 052', NULL, NULL, -29.796853, 30.990353),
(292, 'KZN::KZN CCTV N2 037', NULL, NULL, -29.739517, 31.047244),
(293, 'KZN::KZN CCTV N2 041', NULL, NULL, -29.700197, 31.069783),
(294, 'KZN::KZN CCTV N2 031', NULL, NULL, -29.770589, 30.998733),
(295, 'KZN::KZN CCTV N2 042', NULL, NULL, -29.691178, 31.083411),
(296, 'KZN::KZN CCTV N2 030', NULL, NULL, -29.7768, 30.999019),
(297, 'KZN::KZN CCTV N2 043', NULL, NULL, -29.685281, 31.088503),
(298, 'KZN::KZN CCTV N2 050', NULL, NULL, -29.602156, 31.137858),
(299, 'KZN::KZN CCTV N2 017', NULL, NULL, -29.878439, 30.951131),
(300, 'KZN::KZN CCTV N2 007', NULL, NULL, -29.93435, 30.95192357),
(301, 'KZN::KZN CCTV N2 047', NULL, NULL, -29.639342, 31.111661),
(302, 'KZN::KZN CCTV N2 026', NULL, NULL, -29.8209, 30.967667),
(303, 'KZN::KZN CCTV N2 040', NULL, NULL, -29.707617, 31.0681),
(304, 'KZN::KZN CCTV N2 015', NULL, NULL, -29.889267, 30.945967),
(305, 'KZN::KZN CCTV N2 038', NULL, NULL, -29.733933, 31.054606),
(306, 'KZN::KZN CCTV N2 013', NULL, NULL, -29.894272, 30.951119),
(307, 'KZN::KZN CCTV N2 022', NULL, NULL, -29.839661, 30.956236),
(308, 'KZN::KZN CCTV N2 045', NULL, NULL, -29.662414, 31.101094),
(309, 'KZN::KZN CCTV N2 011', NULL, NULL, -29.911417, 30.949636),
(310, 'KZN::KZN CCTV N2 025', NULL, NULL, -29.825925, 30.967211),
(311, 'KZN::KZN CCTV N2 008', NULL, NULL, -29.934492, 30.95199465),
(312, 'KZN::KZN CCTV N2 002', NULL, NULL, -29.963128, 30.946439),
(313, 'KZN::KZN CCTV N2 006', NULL, NULL, -29.943606, 30.950719),
(314, 'KZN::KZN CCTV N2 049', NULL, NULL, -29.617078, 31.131289),
(315, 'KZN::KZN CCTV N2 003', NULL, NULL, -29.95298, 30.94753012),
(316, 'KZN::KZN CCTV N2 035', NULL, NULL, -29.749778, 31.027039),
(317, 'KZN::KZN CCTV N2 027', NULL, NULL, -29.814392, 30.974072),
(318, 'KZN::KZN CCTV N2 039', NULL, NULL, -29.723967, 31.058989),
(319, 'KZN::KZN CCTV N2 018', NULL, NULL, -29.868214, 30.951131),
(320, 'KZN::KZN CCTV N2 021', NULL, NULL, -29.849636, 30.954086),
(321, 'KZN::KZN CCTV N2 005', NULL, NULL, -29.947203, 30.94805),
(322, 'KZN::KZN CCTV N2 023', NULL, NULL, -29.830575, 30.961181),
(323, 'KZN::KZN CCTV N2 028', NULL, NULL, -29.808858, 30.976072),
(324, 'KZN::KZN CCTV N2 049 Fixed', NULL, NULL, -29.616793, 31.13130033),
(325, 'KZN::KZN CCTV N2 046', NULL, NULL, -29.651253, 31.104756),
(326, 'KZN::KZN CCTV N2 014', NULL, NULL, -29.892122, 30.947617),
(327, 'KZN::KZN CCTV N2 052 Fixed', NULL, NULL, -29.796835, 30.99012091),
(328, 'KZN::KZN CCTV N2 029 Fixed', NULL, NULL, -29.789249, 30.99577501),
(329, 'KZN::KZN CCTV N2 012 Fixed', NULL, NULL, -29.902421, 30.95245063),
(330, 'KZN::KZN CCTV N2 0002A', NULL, NULL, -29.959925, 30.9468),
(331, 'KZN::KZN CCTV N2 0010A', NULL, NULL, -29.921053, 30.948361),
(332, 'KZN::KZN CCTV N2 0002B', NULL, NULL, -29.958503, 30.948425),
(333, 'KZN::KZN CCTV N3 0027A', NULL, NULL, -29.817597, 30.970667),
(334, 'KZN::KZN CCTV N3 0101A', NULL, NULL, -29.840164, 30.970647),
(335, 'KZN::KZN CCTV N2 0043A', NULL, NULL, -29.675267, 31.094544),
(336, 'KZN::KZN CCTV N3 123', NULL, NULL, -29.822444, 30.808219),
(337, 'KZN::KZN CCTV N3 108', NULL, NULL, -29.842197, 30.918181),
(338, 'KZN::KZN CCTV N3 140 Fixed', NULL, NULL, -29.768462, 30.68225562),
(339, 'KZN::KZN CCTV N3 155', NULL, NULL, -29.731731, 30.568817),
(340, 'KZN::KZN CCTV N3 118', NULL, NULL, -29.833419, 30.851381),
(341, 'KZN::KZN CCTV N3 136', NULL, NULL, -29.778092, 30.708381),
(342, 'KZN::KZN CCTV N3 106', NULL, NULL, -29.846742, 30.926664),
(343, 'KZN::KZN CCTV N3 130', NULL, NULL, -29.803908, 30.746331),
(344, 'KZN::KZN CCTV N3 102', NULL, NULL, -29.840662, 30.94772994),
(345, 'KZN::KZN CCTV N3 103', NULL, NULL, -29.840629, 30.94781711),
(346, 'KZN::KZN CCTV N3 125', NULL, NULL, -29.8259, 30.79005),
(347, 'KZN::KZN CCTV N3 0211b', NULL, NULL, -29.637684, 30.41529402),
(348, 'KZN::KZN CCTV N3 140', NULL, NULL, -29.768383, 30.682397),
(349, 'KZN::KZN CCTV N3 0132', NULL, NULL, -29.788122, 30.72767078),
(350, 'KZN::KZN CCTV N3 133', NULL, NULL, -29.787633, 30.719553),
(351, 'KZN::KZN CCTV N3 115', NULL, NULL, -29.838711, 30.870253),
(352, 'KZN::KZN CCTV N3 110', NULL, NULL, -29.836433, 30.907581),
(353, 'KZN::KZN CCTV N3 109', NULL, NULL, -29.840508, 30.91444909),
(354, 'KZN::KZN CCTV N3 134', NULL, NULL, -29.784217, 30.712003),
(355, 'KZN::KZN CCTV N3 141', NULL, NULL, -29.763294, 30.679161),
(356, 'KZN::KZN CCTV N3 153', NULL, NULL, -29.73225, 30.591119),
(357, 'KZN::KZN CCTV N3 114', NULL, NULL, -29.833978, 30.882361),
(358, 'KZN::KZN CCTV N3 147', NULL, NULL, -29.741939, 30.632661),
(359, 'KZN::KZN CCTV N3 156', NULL, NULL, -29.730292, 30.553469),
(360, 'KZN::KZN CCTV N3 148', NULL, NULL, -29.741425, 30.625581),
(361, 'KZN::KZN CCTV N3 208A', NULL, NULL, -29.657998, 30.45385614),
(362, 'KZN::KZN CCTV N3 146', NULL, NULL, -29.736331, 30.647133),
(363, 'KZN::KZN CCTV N3 149', NULL, NULL, -29.738911, 30.620769),
(364, 'KZN::KZN CCTV N3 121', NULL, NULL, -29.826775, 30.820706),
(365, 'KZN::KZN CCTV N3 113', NULL, NULL, -29.833759, 30.89369013),
(366, 'KZN::KZN CCTV N3 117', NULL, NULL, -29.836764, 30.856161),
(367, 'KZN::KZN CCTV N3 128', NULL, NULL, -29.809048, 30.75680091),
(368, 'KZN::KZN CCTV N3 119', NULL, NULL, -29.829975, 30.843258),
(369, 'KZN::KZN CCTV N3 142', NULL, NULL, -29.757711, 30.666731),
(370, 'KZN::KZN CCTV N3 127A', NULL, NULL, -29.814294, 30.7716),
(371, 'KZN::KZN CCTV N3 104', NULL, NULL, -29.844875, 30.941044),
(372, 'KZN::KZN CCTV N3 131', NULL, NULL, -29.795189, 30.736419),
(373, 'KZN::KZN CCTV N3 124', NULL, NULL, -29.825517, 30.795167),
(374, 'KZN::KZN CCTV N3 137', NULL, NULL, -29.77795, 30.70185),
(375, 'KZN::KZN CCTV N3 135', NULL, NULL, -29.783453, 30.71205),
(376, 'KZN::KZN CCTV N3 101', NULL, NULL, -29.838778, 30.966081),
(377, 'KZN::KZN CCTV N3 150', NULL, NULL, -29.737072, 30.606358),
(378, 'KZN::KZN CCTV N3 151', NULL, NULL, -29.737444, 30.606075),
(379, 'KZN::KZN CCTV N3 139', NULL, NULL, -29.770944, 30.691219),
(380, 'KZN::KZN CCTV N3 129', NULL, NULL, -29.804111, 30.7463),
(381, 'KZN::KZN CCTV N3 0205A', NULL, NULL, -29.707639, 30.49609825),
(382, 'KZN::KZN CCTV N3 112', NULL, NULL, -29.833794, 30.89378669),
(383, 'KZN::KZN CCTV N3 111', NULL, NULL, -29.835894, 30.899469),
(384, 'KZN::KZN CCTV N3 144', NULL, NULL, -29.752203, 30.665292),
(385, 'KZN::KZN CCTV N3 120', NULL, NULL, -29.827686, 30.8344),
(386, 'KZN::KZN CCTV N3 124 Fixed', NULL, NULL, -29.825415, 30.79516053),
(387, 'KZN::KZN CCTV N3 226', NULL, NULL, -29.827833, 30.833572),
(388, 'KZN::KZN CCTV N3 107', NULL, NULL, -29.843986, 30.921575),
(389, 'KZN::KZN CCTV N3 126', NULL, NULL, -29.822097, 30.779992),
(390, 'KZN::KZN CCTV N3 116', NULL, NULL, -29.836392, 30.863311),
(391, 'KZN::KZN CCTV N3 105', NULL, NULL, -29.848917, 30.931936),
(392, 'KZN::KZN CCTV N3 137 Fixed', NULL, NULL, -29.778112, 30.70182234),
(393, 'KZN::KZN CCTV N3 127', NULL, NULL, -29.814177, 30.7718186),
(394, 'KZN::KZN CCTV N3 154', NULL, NULL, -29.734106, 30.582572),
(395, 'KZN::KZN CCTV N3 122', NULL, NULL, -29.822033, 30.808219),
(396, 'KZN::KZN CCTV N3 145', NULL, NULL, -29.740517, 30.659089),
(397, 'KZN::KZN CCTV N3 152', NULL, NULL, -29.732081, 30.597772),
(398, 'KZN::KZN CCTV N3 143', NULL, NULL, -29.757781, 30.66605),
(399, 'KZN::KZN CCTV N3 138', NULL, NULL, -29.7738, 30.695267),
(400, 'KZN::KZN CCTV N3 0201a', NULL, NULL, -29.731594, 30.52145183),
(401, 'KZN::KZN CCTV N3 147A', NULL, NULL, -29.742374, 30.62777727),
(402, 'KZN::KZN CCTV N3 0202A', NULL, NULL, -29.729655, 30.51433458),
(403, 'KZN::KZN CCTV N3 207', NULL, NULL, -29.681083, 30.472833),
(404, 'KZN::KZN CCTV N3 0209', NULL, NULL, -29.6463, 30.443383),
(405, 'KZN::KZN CCTV N3 0203', NULL, NULL, -29.72, 30.4982),
(406, 'KZN::KZN CCTV N3 0204', NULL, NULL, -29.714681, 30.495539),
(407, 'KZN::KZN CCTV N3 0211', NULL, NULL, -29.637183, 30.414317),
(408, 'KZN::KZN CCTV N3 0208', NULL, NULL, -29.658547, 30.454575),
(409, 'KZN::KZN CCTV N3 0206', NULL, NULL, -29.690992, 30.481628),
(410, 'KZN::KZN CCTV N3 0205', NULL, NULL, -29.700792, 30.490825),
(411, 'KZN::KZN CCTV N3 0210', NULL, NULL, -29.647214, 30.433472),
(412, 'KZN::KZN CCTV N3 0201', NULL, NULL, -29.730083, 30.53635),
(413, 'KZN::KZN CCTV N3 0202', NULL, NULL, -29.730014, 30.514878),
(414, 'KZN::KZN CCTV N3 0210b', NULL, NULL, -29.643933, 30.427825),
(415, 'KZN::KZN CCTV N2/N3 0022B', NULL, NULL, -29.84116, 30.9568119),
(416, 'KZN::KZN CCTV N2/N3 0022C', NULL, NULL, -29.84107, 30.9569098),
(417, 'WC::WC CCTV N2 901', NULL, NULL, -33.968097, 18.582023),
(418, 'WC::WC CCTV N2 902', NULL, NULL, -33.968635, 18.590041),
(419, 'WC::WC CCTV N2 406A', NULL, NULL, -33.940246, 18.45315679),
(420, 'WC::WC CCTV N1 091', NULL, NULL, -33.916641, 18.43089848),
(421, 'WC::WC CCTV N2 201', NULL, NULL, -33.947078, 18.46639484),
(422, 'WC::WC CCTV M5 504', NULL, NULL, -33.933246, 18.480156),
(423, 'WC::WC CCTV M5 503', NULL, NULL, -33.92872, 18.479523),
(424, 'WC::WC CCTV M5 502', NULL, NULL, -33.924443, 18.476615),
(425, 'WC::WC CCTV M5 501', NULL, NULL, -33.920585, 18.478939),
(426, 'WC::WC CCTV M5 505', NULL, NULL, -33.939446, 18.484109),
(427, 'WC::WC CCTV M5 500A', NULL, NULL, -33.916937, 18.48169013),
(428, 'WC::WC CCTV M5 52', NULL, NULL, -33.937586, 18.483364),
(429, 'WC::WC CCTV M5 506', NULL, NULL, -33.946551, 18.485163),
(430, 'WC::WC CCTV M5 500', NULL, NULL, -33.917041, 18.481755),
(431, 'WC::WC CCTV M5 501A', NULL, NULL, -33.920857, 18.47882419),
(432, 'WC::WC CCTV N1 166', NULL, NULL, -33.887039, 18.573864),
(433, 'WC::WC CCTV N1 801', NULL, NULL, -33.916365, 18.428777),
(434, 'WC::WC CCTV N1 183', NULL, NULL, -33.888723, 18.62094372),
(435, 'WC::WC CCTV N1 117', NULL, NULL, -33.875746, 18.662153),
(436, 'WC::WC CCTV N1 108', NULL, NULL, -33.888751, 18.563754),
(437, 'WC::WC CCTV N1 152', NULL, NULL, -33.919673, 18.46968054),
(438, 'WC::WC CCTV N1 803A', NULL, NULL, -33.92177, 18.44964),
(439, 'WC::WC CCTV N1 133', NULL, NULL, -33.796366, 18.883464),
(440, 'WC::WC CCTV N1 176', NULL, NULL, -33.886089, 18.595045),
(441, 'WC::WC CCTV N1 169', NULL, NULL, -33.886647, 18.576173),
(442, 'WC::WC CCTV N1 124', NULL, NULL, -33.835222, 18.73596),
(443, 'WC::WC CCTV N1 167', NULL, NULL, -33.88694, 18.57379451),
(444, 'WC::WC CCTV N1 104', NULL, NULL, -33.893983, 18.516742),
(445, 'WC::WC CCTV N1 102', NULL, NULL, -33.906101, 18.50384786),
(446, 'WC::WC CCTV N1 140', NULL, NULL, -33.742186, 19.005033),
(447, 'WC::WC CCTV N1 172', NULL, NULL, -33.886683, 18.57633322),
(448, 'WC::WC CCTV N1 126', NULL, NULL, -33.827426, 18.763876),
(449, 'WC::WC CCTV N1 092', NULL, NULL, -33.921052, 18.43755438),
(450, 'WC::WC CCTV N1 192', NULL, NULL, -33.799102, 18.86681377),
(451, 'WC::WC CCTV N1 194', NULL, NULL, -33.790774, 18.91039162),
(452, 'WC::WC CCTV N1 195', NULL, NULL, -33.788892, 18.91955807),
(453, 'WC::WC CCTV N1 198', NULL, NULL, -33.863042, 18.68783265),
(454, 'WC::WC CCTV N1 112', NULL, NULL, -33.889582, 18.602018),
(455, 'WC::WC CCTV N1 165', NULL, NULL, -33.887092, 18.5739085),
(456, 'WC::WC CCTV N1 127', NULL, NULL, -33.82286, 18.780191),
(457, 'WC::WC CCTV N1 174', NULL, NULL, -33.886046, 18.595059),
(458, 'WC::WC CCTV N1 173', NULL, NULL, -33.886098, 18.59488606),
(459, 'WC::WC CCTV N1 128', NULL, NULL, -33.820498, 18.788607),
(460, 'WC::WC CCTV N1 135', NULL, NULL, -33.788845, 18.920094),
(461, 'WC::WC CCTV N1 103', NULL, NULL, -33.900678, 18.5092),
(462, 'WC::WC CCTV N1 179', NULL, NULL, -33.887962, 18.59871491),
(463, 'WC::WC CCTV N1 156', NULL, NULL, -33.914057, 18.49398002),
(464, 'WC::WC CCTV N1 129', NULL, NULL, -33.816659, 18.802364),
(465, 'WC::WC CCTV N1 104A', NULL, NULL, -33.888617, 18.522455),
(466, 'WC::WC CCTV N1 182', NULL, NULL, -33.88913, 18.615661),
(467, 'WC::WC CCTV N1 181', NULL, NULL, -33.88887, 18.61562222),
(468, 'WC::WC CCTV N1 175', NULL, NULL, -33.88617, 18.59502285),
(469, 'WC::WC CCTV N1 170', NULL, NULL, -33.88657, 18.5760194),
(470, 'WC::WC CCTV N1 164', NULL, NULL, -33.889759, 18.54335814),
(471, 'WC::WC CCTV N1 132', NULL, NULL, -33.800062, 18.862343),
(472, 'WC::WC CCTV N1 161', NULL, NULL, -33.889012, 18.54191511),
(473, 'WC::WC CCTV N1 139', NULL, NULL, -33.75013, 18.993039),
(474, 'WC::WC CCTV N1 109', NULL, NULL, -33.887924, 18.569955),
(475, 'WC::WC CCTV N1 803', NULL, NULL, -33.921324, 18.447523),
(476, 'WC::WC CCTV N1 185', NULL, NULL, -33.888547, 18.62088739),
(477, 'WC::WC CCTV N1 154', NULL, NULL, -33.916684, 18.48640546),
(478, 'WC::WC CCTV N1 184', NULL, NULL, -33.888528, 18.62119317),
(479, 'WC::WC CCTV N1 180', NULL, NULL, -33.888128, 18.59866663),
(480, 'WC::WC CCTV N1 806', NULL, NULL, -33.919429, 18.470145),
(481, 'WC::WC CCTV N1 116', NULL, NULL, -33.88078, 18.650523),
(482, 'WC::WC CCTV N1 115', NULL, NULL, -33.883247, 18.644705),
(483, 'WC::WC CCTV N1 137', NULL, NULL, -33.776985, 18.955835),
(484, 'WC::WC CCTV N1 114', NULL, NULL, -33.887503, 18.634655),
(485, 'WC::WC CCTV N1 163', NULL, NULL, -33.88964, 18.543308),
(486, 'WC::WC CCTV N1 155', NULL, NULL, -33.914122, 18.493903),
(487, 'WC::WC CCTV N1 106A', NULL, NULL, -33.88511, 18.53351),
(488, 'WC::WC CCTV N1 141', NULL, NULL, -33.74207, 19.016891),
(489, 'WC::WC CCTV N1 807A', NULL, NULL, -33.917836, 18.47777277),
(490, 'WC::WC CCTV N1 117A', NULL, NULL, -33.875553, 18.66180047),
(491, 'WC::WC CCTV N1 157', NULL, NULL, -33.894519, 18.51642474),
(492, 'WC::WC CCTV N1 107', NULL, NULL, -33.891157, 18.547739),
(493, 'WC::WC CCTV N1 106', NULL, NULL, -33.883407, 18.531423),
(494, 'WC::WC CCTV N1 186', NULL, NULL, -33.888708, 18.62118646),
(495, 'WC::WC CCTV N1 168', NULL, NULL, -33.887108, 18.5738106),
(496, 'WC::WC CCTV N1 802', NULL, NULL, -33.921726, 18.442385),
(497, 'WC::WC CCTV N1 804', NULL, NULL, -33.920754, 18.456312),
(498, 'WC::WC CCTV N1 101', NULL, NULL, -33.914174, 18.494326),
(499, 'WC::WC CCTV N1 142', NULL, NULL, -33.744089, 19.024264),
(500, 'WC::WC CCTV N1 177', NULL, NULL, -33.888115, 18.59864249),
(501, 'WC::WC CCTV N1 111', NULL, NULL, -33.886059, 18.59516099),
(502, 'WC::WC CCTV N1 805', NULL, NULL, -33.920717, 18.462706),
(503, 'WC::WC CCTV N1 171', NULL, NULL, -33.886704, 18.57621252),
(504, 'WC::WC CCTV N1 134', NULL, NULL, -33.790771, 18.910622),
(505, 'WC::WC CCTV N1 125', NULL, NULL, -33.83141, 18.749523),
(506, 'WC::WC CCTV N1 122', NULL, NULL, -33.845201, 18.71475),
(507, 'WC::WC CCTV N1 105', NULL, NULL, -33.885109, 18.528894),
(508, 'WC::WC CCTV N1 151', NULL, NULL, -33.919431, 18.47074136),
(509, 'WC::WC CCTV N1 130', NULL, NULL, -33.811139, 18.822129),
(510, 'WC::WC CCTV N1 105A', NULL, NULL, -33.88621, 18.53131),
(511, 'WC::WC CCTV N1 121', NULL, NULL, -33.851824, 18.704637),
(512, 'WC::WC CCTV N1 120', NULL, NULL, -33.857704, 18.695539),
(513, 'WC::WC CCTV N1 110', NULL, NULL, -33.884572, 18.58439),
(514, 'WC::WC CCTV N1 123', NULL, NULL, -33.839591, 18.723487),
(515, 'WC::WC CCTV N1 136', NULL, NULL, -33.784327, 18.943164),
(516, 'WC::WC CCTV N1 178', NULL, NULL, -33.888009, 18.598609),
(517, 'WC::WC CCTV N1 131', NULL, NULL, -33.806685, 18.838683),
(518, 'WC::WC CCTV N1 162', NULL, NULL, -33.889219, 18.542346),
(519, 'WC::WC CCTV N1 119', NULL, NULL, -33.866461, 18.682861),
(520, 'WC::WC CCTV N1 112A', NULL, NULL, -33.889214, 18.615589),
(521, 'WC::WC CCTV N1 138', NULL, NULL, -33.764959, 18.972884),
(522, 'WC::WC CCTV N1 113', NULL, NULL, -33.888677, 18.620942),
(523, 'WC::WC CCTV N1 118', NULL, NULL, -33.869291, 18.676183),
(524, 'WC::WC CCTV N1 153', NULL, NULL, -33.916835, 18.48646983),
(525, 'WC::WC CCTV N1 143', NULL, NULL, -33.74555, 19.05990064),
(526, 'WC::WC CCTV N1 158', NULL, NULL, -33.893723, 18.51728707),
(527, 'WC::WC CCTV N1 807', NULL, NULL, -33.917444, 18.478058),
(528, 'WC::WC CCTV N1 100A', NULL, NULL, -33.916768, 18.4868279),
(529, 'WC::WC CCTV M5 500B', NULL, NULL, -33.916712, 18.48256856),
(530, 'WC::WC CCTV N2 225', NULL, NULL, -34.034985, 18.713023),
(531, 'WC::WC CCTV N2 402', NULL, NULL, -33.926877, 18.433248),
(532, 'WC::WC CCTV N2 212', NULL, NULL, -33.960505, 18.558693),
(533, 'WC::WC CCTV N2 281', NULL, NULL, -34.007833, 18.648378),
(534, 'WC::WC CCTV N2 261', NULL, NULL, -34.133515, 18.929244),
(535, 'WC::WC CCTV N2 406C', NULL, NULL, -33.93797, 18.44372),
(536, 'WC::WC CCTV N2 201D', NULL, NULL, -33.945612, 18.46593752),
(537, 'WC::WC CCTV N2 206', NULL, NULL, -33.95114, 18.496668),
(538, 'WC::WC CCTV N2 406', NULL, NULL, -33.941068, 18.457621),
(539, 'WC::WC CCTV N2 218', NULL, NULL, -33.993749, 18.614368),
(540, 'WC::WC CCTV N2 206A', NULL, NULL, -33.95011, 18.50116),
(541, 'WC::WC CCTV N2 406B', NULL, NULL, -33.94061, 18.44911),
(542, 'WC::WC CCTV N2 263', NULL, NULL, -34.127277, 18.933475),
(543, 'WC::WC CCTV N2 230', NULL, NULL, -34.056915, 18.770905),
(544, 'WC::WC CCTV N2 408', NULL, NULL, -33.942998, 18.463699),
(545, 'WC::WC CCTV N2 910', NULL, NULL, -34.085015, 18.834943),
(546, 'WC::WC CCTV N2 220AE', NULL, NULL, -34.009001, 18.65185216),
(547, 'WC::WC CCTV N2 264', NULL, NULL, -34.132644, 18.937528),
(548, 'WC::WC CCTV N2 235', NULL, NULL, -34.084036, 18.828376),
(549, 'WC::WC CCTV N2 202', NULL, NULL, -33.944856, 18.471363),
(550, 'WC::WC CCTV N2 914', NULL, NULL, -34.112227, 18.867031),
(551, 'WC::WC CCTV N2 227', NULL, NULL, -34.042963, 18.734361),
(552, 'WC::WC CCTV N2 284', NULL, NULL, -34.029619, 18.699373),
(553, 'WC::WC CCTV N2 221', NULL, NULL, -34.012277, 18.659105),
(554, 'WC::WC CCTV N2 260', NULL, NULL, -34.135159, 18.923269),
(555, 'WC::WC CCTV N2 287', NULL, NULL, -34.043051, 18.73433411),
(556, 'WC::WC CCTV N2 214T', NULL, NULL, -33.967363, 18.573785),
(557, 'WC::WC CCTV N2 224', NULL, NULL, -34.029816, 18.69963034),
(558, 'WC::WC CCTV N2 204', NULL, NULL, -33.943916, 18.486495),
(559, 'WC::WC CCTV N2 214', NULL, NULL, -33.968224, 18.5741499),
(560, 'WC::WC CCTV N2 229', NULL, NULL, -34.04786, 18.756319),
(561, 'WC::WC CCTV N2 912', NULL, NULL, -34.096497, 18.847413),
(562, 'WC::WC CCTV N2 407', NULL, NULL, -33.943055, 18.460922),
(563, 'WC::WC CCTV N2 232', NULL, NULL, -34.059222, 18.794711),
(564, 'WC::WC CCTV N2 216', NULL, NULL, -33.982541, 18.587856),
(565, 'WC::WC CCTV N2 220A', NULL, NULL, -34.008579, 18.65095362),
(566, 'WC::WC CCTV N2 405A', NULL, NULL, -33.938754, 18.457183),
(567, 'WC::WC CCTV N2 285', NULL, NULL, -34.035367, 18.71374279),
(568, 'WC::WC CCTV N2 266', NULL, NULL, -34.14316, 18.92982),
(569, 'WC::WC CCTV N2 215T', NULL, NULL, -33.975232, 18.58060464),
(570, 'WC::WC CCTV N2 286', NULL, NULL, -34.039013, 18.7233),
(571, 'WC::WC CCTV N2 293', NULL, NULL, -34.06746, 18.80862995),
(572, 'WC::WC CCTV N2 201A', NULL, NULL, -33.946709, 18.466556),
(573, 'WC::WC CCTV N2 203', NULL, NULL, -33.943849, 18.47619),
(574, 'WC::WC CCTV N2 231', NULL, NULL, -34.059657, 18.781417),
(575, 'WC::WC CCTV N2 404', NULL, NULL, -33.933088, 18.446818),
(576, 'WC::WC CCTV N2 228T', NULL, NULL, -34.044028, 18.7457174),
(577, 'WC::WC CCTV N2 218A', NULL, NULL, -33.99772, 18.62481),
(578, 'WC::WC CCTV N2 207', NULL, NULL, -33.949615, 18.509329),
(579, 'WC::WC CCTV N2 262', NULL, NULL, -34.128478, 18.930115),
(580, 'WC::WC CCTV N2 916', NULL, NULL, -34.122993, 18.885714),
(581, 'WC::WC CCTV N2 215', NULL, NULL, -33.974746, 18.580338),
(582, 'WC::WC CCTV N2 265', NULL, NULL, -34.138258, 18.932196),
(583, 'WC::WC CCTV N2 267', NULL, NULL, -34.148975, 18.92825),
(584, 'WC::WC CCTV N2 233', NULL, NULL, -34.067109, 18.80803585),
(585, 'WC::WC CCTV N2 403', NULL, NULL, -33.931755, 18.438937),
(586, 'WC::WC CCTV N2 228', NULL, NULL, -34.044028, 18.746191),
(587, 'WC::WC CCTV N2 205', NULL, NULL, -33.948398, 18.489647),
(588, 'WC::WC CCTV N2 222', NULL, NULL, -34.019112, 18.67302954),
(589, 'WC::WC CCTV N2 216T', NULL, NULL, -33.982645, 18.58861103),
(590, 'WC::WC CCTV N2 220', NULL, NULL, -34.006233, 18.64577159),
(591, 'WC::WC CCTV N2 290', NULL, NULL, -34.05704, 18.77089262),
(592, 'WC::WC CCTV N2 220AW', NULL, NULL, -34.009229, 18.65178376),
(593, 'WC::WC CCTV N2 911', NULL, NULL, -34.089765, 18.840188),
(594, 'WC::WC CCTV N2 234', NULL, NULL, -34.077259, 18.821215),
(595, 'WC::WC CCTV N2 203A', NULL, NULL, -33.94371, 18.48146),
(596, 'WC::WC CCTV N2 201C', NULL, NULL, -33.948053, 18.466558),
(597, 'WC::WC CCTV N2 208', NULL, NULL, -33.950055, 18.522268),
(598, 'WC::WC CCTV N2 601', NULL, NULL, -33.951313, 18.466146),
(599, 'WC::WC CCTV N2 211', NULL, NULL, -33.958398, 18.550236),
(600, 'WC::WC CCTV N2 282', NULL, NULL, -34.018839, 18.673232),
(601, 'WC::WC CCTV N2 217', NULL, NULL, -33.988104, 18.600031),
(602, 'WC::WC CCTV N2 913', NULL, NULL, -34.10596, 18.857375),
(603, 'WC::WC CCTV N2 221T', NULL, NULL, -34.012404, 18.65917727),
(604, 'WC::WC CCTV N2 269', NULL, NULL, -34.15294, 18.940169),
(605, 'WC::WC CCTV N2 219', NULL, NULL, -33.99994, 18.630038),
(606, 'WC::WC CCTV N2 917', NULL, NULL, -34.129618, 18.9062),
(607, 'WC::WC CCTV N2 209', NULL, NULL, -33.952574, 18.532803),
(608, 'WC::WC CCTV N2 226', NULL, NULL, -34.039705, 18.72410148),
(609, 'WC::WC CCTV N2 915', NULL, NULL, -34.117188, 18.87617),
(610, 'WC::WC CCTV N2 213', NULL, NULL, -33.96282, 18.566441),
(611, 'WC::WC CCTV N2 201B', NULL, NULL, -33.946481, 18.4671016),
(612, 'WC::WC CCTV N2 210', NULL, NULL, -33.954769, 18.541759),
(613, 'WC::WC CCTV N2 223', NULL, NULL, -34.025155, 18.687987),
(614, 'WC::WC CCTV N2 268', NULL, NULL, -34.149923, 18.932668),
(615, 'WC::WC CCTV N2 405', NULL, NULL, -33.936412, 18.451199),
(616, 'WC::WC CCTV N2 220T', NULL, NULL, -34.006104, 18.645758),
(617, 'WC::WC CCTV N7 703', NULL, NULL, -33.847241, 18.533628),
(618, 'WC::WC CCTV N7 702', NULL, NULL, -33.862834, 18.529873),
(619, 'WC::WC CCTV N7 701', NULL, NULL, -33.873073, 18.529755),
(620, 'WC::WC CCTV N7 704', NULL, NULL, -33.830563, 18.539888),
(621, 'WC::WC CCTV N7 705', NULL, NULL, -33.818393, 18.54425668),
(622, 'WC::WC CCTV N7 705T', NULL, NULL, -33.818666, 18.54415342),
(623, 'WC::WC CCTV N7 705T2', NULL, NULL, -33.81781, 18.54447796),
(624, 'WC::WC CCTV N7 706T', NULL, NULL, -33.809723, 18.54721248),
(625, 'WC::WC CCTV N7 706', NULL, NULL, -33.809389, 18.54729026),
(626, 'WC::WC CCTV R300 303W', NULL, NULL, -33.994752, 18.63957569),
(627, 'WC::WC CCTV R300 303E', NULL, NULL, -33.994336, 18.64000484),
(628, 'WC::WC CCTV N2 300', NULL, NULL, -34.014023, 18.61971795),
(629, 'WC::WC CCTV R300 309W', NULL, NULL, -33.928435, 18.66279423),
(630, 'WC::WC CCTV N2 300W', NULL, NULL, -34.013879, 18.62017527),
(631, 'WC::WC CCTV R300 313', NULL, NULL, -33.888562, 18.675731),
(632, 'WC::WC CCTV R300 307E2', NULL, NULL, -33.950888, 18.65822508),
(633, 'WC::WC CCTV R300 311', NULL, NULL, -33.906332, 18.673499),
(634, 'WC::WC CCTV R300 309', NULL, NULL, -33.927205, 18.66281569),
(635, 'WC::WC CCTV R300 303', NULL, NULL, -33.994614, 18.640309),
(636, 'WC::WC CCTV R300 309A', NULL, NULL, -33.927639, 18.663144),
(637, 'WC::WC CCTV R300 304', NULL, NULL, -33.986641, 18.648421),
(638, 'WC::WC CCTV R300 303A', NULL, NULL, -33.995071, 18.63955155),
(639, 'WC::WC CCTV R300 302', NULL, NULL, -34.001693, 18.632949),
(640, 'WC::WC CCTV R300 307W2', NULL, NULL, -33.950151, 18.65837797),
(641, 'WC::WC CCTV R300 314', NULL, NULL, -33.878902, 18.673078),
(642, 'WC::WC CCTV R300 310', NULL, NULL, -33.916396, 18.667022),
(643, 'WC::WC CCTV R300 312', NULL, NULL, -33.896509, 18.678005),
(644, 'WC::WC CCTV R300 301', NULL, NULL, -34.008218, 18.626212),
(645, 'WC::WC CCTV R300 309E', NULL, NULL, -33.929083, 18.66243079),
(646, 'WC::WC CCTV R300 308', NULL, NULL, -33.942457, 18.660153),
(647, 'WC::WC CCTV R300 306W', NULL, NULL, -33.968052, 18.65473017),
(648, 'WC::WC CCTV R300 307W1', NULL, NULL, -33.950473, 18.65831092),
(649, 'WC::WC CCTV R300 315', NULL, NULL, -33.873918, 18.672437),
(650, 'WC::WC CCTV N2 300E', NULL, NULL, -34.013487, 18.620012),
(651, 'WC::WC CCTV R300 306E', NULL, NULL, -33.967422, 18.655058),
(652, 'WC::WC CCTV R300 307', NULL, NULL, -33.951093, 18.65818351),
(653, 'WC::WC CCTV R300 306A', NULL, NULL, -33.967542, 18.65460678),
(654, 'WC::WC CCTV R300 305', NULL, NULL, -33.978223, 18.652816),
(655, 'WC::WC CCTV R300 306', NULL, NULL, -33.967907, 18.65475967),
(656, 'WC::WC CCTV N1 100', NULL, NULL, -33.918114, 18.48127707),
(657, 'WC::WC CCTV N1 159', NULL, NULL, -33.885157, 18.52868646),
(658, 'WC::WC CCTV N1 160', NULL, NULL, -33.88493, 18.52905794),
(659, 'WC::WC CCTV R300 315A', NULL, NULL, -33.873691, 18.67253065),
(660, 'WC::WC CCTV R300 307A', NULL, NULL, -33.949546, 18.65854963),
(661, 'WC::WC CCTV R300 307E1', NULL, NULL, -33.950952, 18.65836858);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `traffic_camera_info`
--
ALTER TABLE `traffic_camera_info`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `traffic_camera_info`
--
ALTER TABLE `traffic_camera_info`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1024;
/*!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 */;
|
-- sql_current_plan.sql
-- must first run dynamic_plan_table.sql
-- get hash value from sql_current.sql
--
-- from Tom Kyte - http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:10353453905351
-- plug in the hash value
@clears
set line 200
spool sql_current_plan.txt
select plan_table_output
from
TABLE(
dbms_xplan.display (
'dynamic_plan_table',
(
select min(x) x
from (
select rawtohex(address)||'_'||child_number x
from v$sql
where hash_value = 3296599010
)
),
'serial'
)
)
/
spool off
|
/*==============================================================*/
/* DBMS name: MySQL 5.0 */
/* Created on: 2020/3/27 15:10:18 */
/*==============================================================*/
drop table if exists CheckIn;
drop table if exists Class;
drop table if exists Dictionary;
drop table if exists DictionaryType;
drop table if exists Info;
drop table if exists Menu;
drop table if exists Role;
drop table if exists RoleRight;
drop table if exists StdClass;
drop table if exists User;
drop table if exists UserRight;
drop table if exists UserRole;
/*==============================================================*/
/* Table: CheckIn */
/*==============================================================*/
create table CheckIn
(
id int not null,
UserId bigint,
ClassId bigint,
CheckDate datetime,
CheckState int,
primary key (id)
);
/*==============================================================*/
/* Table: Class */
/*==============================================================*/
create table Class
(
ClassId int not null,
UserId bigint,
ClassNum int,
ClassDiscription varchar(0),
CreateTime datetime,
UpdateTime datetime,
LastUpdateUserId bigint,
primary key (ClassId)
);
/*==============================================================*/
/* Table: Dictionary */
/*==============================================================*/
create table Dictionary
(
DictionaryId int not null,
UserId bigint,
DirctionaryTypeId int,
keyword varchar(0),
type int,
value varchar(0),
discription varchar(0),
is_defaule int,
create_date datetime,
last_update datetime,
primary key (DictionaryId)
);
/*==============================================================*/
/* Table: DictionaryType */
/*==============================================================*/
create table DictionaryType
(
DirctionaryTypeId int not null,
name varchar(0),
primary key (DirctionaryTypeId)
);
/*==============================================================*/
/* Table: Info */
/*==============================================================*/
create table Info
(
info_id int not null,
UserId bigint,
RoleId int,
info_content varchar(0),
type int,
primary key (info_id)
);
/*==============================================================*/
/* Table: Menu */
/*==============================================================*/
create table Menu
(
Id int not null,
Right_Key varchar(255) not null,
ParentKey varchar(255),
Right_Url varchar(255),
Right_Name varchar(255),
Right_Type int,
Right_Status int,
SortIndex int,
AddTime datetime,
LastUpdate datetime,
IconUrl varchar(255),
AddUser varchar(255),
IsDefaultRight int,
primary key (Right_Key)
);
/*==============================================================*/
/* Table: Role */
/*==============================================================*/
create table Role
(
RoleId int not null,
RoleName varchar(255),
CreateDate datetime,
Creator varchar(255),
primary key (RoleId)
);
/*==============================================================*/
/* Table: RoleRight */
/*==============================================================*/
create table RoleRight
(
id int not null,
Right_Key varchar(255),
RoleId int,
primary key (id)
);
/*==============================================================*/
/* Table: StdClass */
/*==============================================================*/
create table StdClass
(
id int not null,
UserId bigint,
ClassId int,
primary key (id)
);
/*==============================================================*/
/* Table: User */
/*==============================================================*/
create table User
(
UserId bigint not null,
UserName varchar(255),
NickName varchar(255),
BornDate date,
CountryId int,
Address varchar(255),
SchoolId int,
Phone bigint,
UserCode bigint,
RealName varchar(255),
UserType int,
primary key (UserId)
);
/*==============================================================*/
/* Table: UserRight */
/*==============================================================*/
create table UserRight
(
Right_Key varchar(255),
Enable_Flag int,
Id int not null,
UserId bigint,
primary key (Id)
);
/*==============================================================*/
/* Table: UserRole */
/*==============================================================*/
create table UserRole
(
Id int not null,
UserId bigint,
RoleId int,
primary key (Id)
);
alter table CheckIn add constraint FK_Reference_10 foreign key (UserId)
references User (UserId) on delete restrict on update restrict;
alter table CheckIn add constraint FK_Reference_11 foreign key (ClassId)
references Class (ClassId) on delete restrict on update restrict;
alter table Class add constraint FK_Reference_7 foreign key (UserId)
references User (UserId) on delete restrict on update restrict;
alter table Dictionary add constraint FK_Reference_14 foreign key (UserId)
references User (UserId) on delete restrict on update restrict;
alter table Dictionary add constraint FK_Reference_15 foreign key (DirctionaryTypeId)
references DictionaryType (DirctionaryTypeId) on delete restrict on update restrict;
alter table Info add constraint FK_Reference_8 foreign key (UserId)
references User (UserId) on delete restrict on update restrict;
alter table Info add constraint FK_Reference_16 foreign key (RoleId)
references Role (RoleId) on delete restrict on update restrict;
alter table RoleRight add constraint FK_Reference_4 foreign key (Right_Key)
references Menu (Right_Key) on delete restrict on update restrict;
alter table RoleRight add constraint FK_Reference_15 foreign key (RoleId)
references Role (RoleId) on delete restrict on update restrict;
alter table StdClass add constraint FK_Reference_12 foreign key (UserId)
references User (UserId) on delete restrict on update restrict;
alter table StdClass add constraint FK_Reference_13 foreign key (ClassId)
references Class (ClassId) on delete restrict on update restrict;
alter table UserRight add constraint FK_Reference_1 foreign key (UserId)
references User (UserId) on delete restrict on update restrict;
alter table UserRight add constraint FK_Reference_2 foreign key (Right_Key)
references Menu (Right_Key) on delete restrict on update restrict;
alter table UserRole add constraint FK_Reference_6 foreign key (UserId)
references User (UserId) on delete restrict on update restrict;
alter table UserRole add constraint FK_Reference_14 foreign key (RoleId)
references Role (RoleId) on delete restrict on update restrict;
|
-- obtener los 5 primeros registros de la tabla
--primera forma
SELECT *
FROM platzi.alumnos
LIMIT 5;
--segunda formas
SELECT *
FROM (
SELECT row_number() over() AS row_id,
*
FROM platzi.alumnos
) AS alumnos_with_row_number
WHERE row_id BETWEEN 1 AND 5;
--tercera forma
SELECT *
FROM platzi.alumnos
FETCH FIRST 5 ROWS ONLY; |
SELECT AP.vend_name, PL.extra_8 AS [CH Ship Dt], PH.ord_dt AS [Marco Order Dt], PL.item_no, PL.qty_ordered, PL.act_unit_cost
FROM dbo.apvenfil_sql AS AP INNER JOIN
dbo.poordhdr_sql AS PH ON AP.vend_no = PH.vend_no INNER JOIN
dbo.poordlin_sql AS PL ON PL.ord_no = PH.ord_no AND PL.vend_no = PH.vend_no INNER JOIN
dbo.humres AS HR ON PL.byr_plnr = HR.res_id LEFT OUTER JOIN
dbo.poshpfil_sql AS PS ON PS.ship_to_cd = PH.ship_to_cd
WHERE (PL.qty_received = PL.qty_ordered) AND (LTRIM(PL.vend_no) IN ('8830', '8859', '9523', '9533')) AND
(PL.receipt_dt > DATEADD(day, - 180, GETDATE())) and
not PL.extra_8 is null
ORDER BY PL.vend_no |
use Northwind
create table Products(
ProductID int,
ProductName varchar(50) not null,
UnitPrice money,--decimal(5,2),
UnitsInStock int,
constraint pk_Products primary key(ProductID),
constraint ck_UnitPrice_Products check(UnitPrice > 0),
constraint ck_UnitsInStock_Products check(UnitsInStock > 0),
)
--drop table products |
-- MySQL Script generated by MySQL Workbench
-- Mon Jun 3 16:50:12 2019
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema db_estaciona_facil
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema db_estaciona_facil
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `db_estaciona_facil` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci ;
USE `db_estaciona_facil` ;
-- -----------------------------------------------------
-- Table `db_estaciona_facil`.`tbl_endereco`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `db_estaciona_facil`.`tbl_endereco` (
`cod_endereco` INT(11) NOT NULL AUTO_INCREMENT,
`logradouro` VARCHAR(55) NOT NULL,
`numero` VARCHAR(10) NOT NULL,
`bairro` VARCHAR(60) NOT NULL,
`cep` VARCHAR(8) NOT NULL,
`cidade` VARCHAR(100) NOT NULL,
`estado` VARCHAR(100) NOT NULL,
PRIMARY KEY (`cod_endereco`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
-- -----------------------------------------------------
-- Table `db_estaciona_facil`.`tbl_fabricante`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `db_estaciona_facil`.`tbl_fabricante` (
`cod_fabricante` INT(11) NOT NULL AUTO_INCREMENT,
`nome` VARCHAR(30) NOT NULL,
PRIMARY KEY (`cod_fabricante`))
ENGINE = InnoDB
AUTO_INCREMENT = 2
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
-- -----------------------------------------------------
-- Table `db_estaciona_facil`.`tbl_mensalista`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `db_estaciona_facil`.`tbl_mensalista` (
`cod_mensalista` INT(11) NOT NULL AUTO_INCREMENT,
`nome` VARCHAR(100) NOT NULL,
`email` VARCHAR(150) NOT NULL,
`cpf` VARCHAR(15) NOT NULL,
PRIMARY KEY (`cod_mensalista`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
-- -----------------------------------------------------
-- Table `db_estaciona_facil`.`tbl_mensalista_endereco`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `db_estaciona_facil`.`tbl_mensalista_endereco` (
`cod_mensalista_endereco` INT(11) NOT NULL AUTO_INCREMENT,
`cod_mensalista` INT(11) NOT NULL,
`cod_endereco` INT(11) NOT NULL,
PRIMARY KEY (`cod_mensalista_endereco`),
INDEX `fk_mensalista_endereco` (`cod_endereco` ASC),
INDEX `fk_endereco_mensalista` (`cod_mensalista` ASC),
CONSTRAINT `fk_endereco_mensalista`
FOREIGN KEY (`cod_mensalista`)
REFERENCES `db_estaciona_facil`.`tbl_mensalista` (`cod_mensalista`),
CONSTRAINT `fk_mensalista_endereco`
FOREIGN KEY (`cod_endereco`)
REFERENCES `db_estaciona_facil`.`tbl_endereco` (`cod_endereco`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
-- -----------------------------------------------------
-- Table `db_estaciona_facil`.`tbl_telefone`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `db_estaciona_facil`.`tbl_telefone` (
`cod_telefone` INT(11) NOT NULL AUTO_INCREMENT,
`telefone` VARCHAR(20) NOT NULL,
PRIMARY KEY (`cod_telefone`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
-- -----------------------------------------------------
-- Table `db_estaciona_facil`.`tbl_mensalista_telefone`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `db_estaciona_facil`.`tbl_mensalista_telefone` (
`cod_mensalista_telefone` INT(11) NOT NULL AUTO_INCREMENT,
`cod_mensalista` INT(11) NOT NULL,
`cod_telefone` INT(11) NOT NULL,
PRIMARY KEY (`cod_mensalista_telefone`),
INDEX `fk_mensalista_telefone` (`cod_telefone` ASC),
INDEX `fk_telefone_mensalista` (`cod_mensalista` ASC),
CONSTRAINT `fk_mensalista_telefone`
FOREIGN KEY (`cod_telefone`)
REFERENCES `db_estaciona_facil`.`tbl_telefone` (`cod_telefone`),
CONSTRAINT `fk_telefone_mensalista`
FOREIGN KEY (`cod_mensalista`)
REFERENCES `db_estaciona_facil`.`tbl_mensalista` (`cod_mensalista`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
-- -----------------------------------------------------
-- Table `db_estaciona_facil`.`tbl_movimentacao`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `db_estaciona_facil`.`tbl_movimentacao` (
`cod_movimento` INT(11) NOT NULL AUTO_INCREMENT,
`placa` VARCHAR(8) NOT NULL,
`modelo_carro` VARCHAR(15) NOT NULL,
`data_hora_entrada` DATETIME NOT NULL,
`data_hora_saida` DATETIME NULL DEFAULT NULL,
`tipo` VARCHAR(10) NULL DEFAULT NULL,
`tempo_permanencia` INT(11) NOT NULL DEFAULT '0',
`valor_pago` DECIMAL(5,2) NOT NULL DEFAULT '0.00',
PRIMARY KEY (`cod_movimento`))
ENGINE = InnoDB
AUTO_INCREMENT = 5
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
-- -----------------------------------------------------
-- Table `db_estaciona_facil`.`tbl_preco`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `db_estaciona_facil`.`tbl_preco` (
`cod_preco` INT(11) NOT NULL AUTO_INCREMENT,
`valor_primeira_hora` DECIMAL(5,2) NOT NULL,
`valor_demais_horas` DECIMAL(5,2) NOT NULL,
`preco_mensal` DECIMAL(5,2) NOT NULL,
`tempo_tolerancia` INT(11) NOT NULL,
`data_fim` DATETIME NULL DEFAULT NULL,
PRIMARY KEY (`cod_preco`))
ENGINE = InnoDB
AUTO_INCREMENT = 2
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
-- -----------------------------------------------------
-- Table `db_estaciona_facil`.`tbl_veiculo`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `db_estaciona_facil`.`tbl_veiculo` (
`cod_veiculo` INT(11) NOT NULL AUTO_INCREMENT,
`placa` VARCHAR(7) NOT NULL,
`modelo_carro` VARCHAR(30) NOT NULL,
`cod_fabricante` INT NOT NULL,
`cod_mensalista` INT NOT NULL,
PRIMARY KEY (`cod_veiculo`),
INDEX `fk_veiculo_fabricante_idx` (`cod_fabricante` ASC),
INDEX `fk_veiculo_mensalista_idx` (`cod_mensalista` ASC),
CONSTRAINT `fk_veiculo_fabricante`
FOREIGN KEY (`cod_fabricante`)
REFERENCES `db_estaciona_facil`.`tbl_fabricante` (`cod_fabricante`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_veiculo_mensalista`
FOREIGN KEY (`cod_mensalista`)
REFERENCES `db_estaciona_facil`.`tbl_mensalista` (`cod_mensalista`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
AUTO_INCREMENT = 3
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
|
ALTER TABLE "EAADMIN"."HARDWARE" ADD COLUMN MULTI_TENANT VARCHAR(1)
;
ALTER TABLE "EAADMIN"."HARDWARE" ADD COLUMN HARDWARE_COMPLEX VARCHAR(20)
;
REORG TABLE EAADMIN.HARDWARE use TEMPSPACE1;
|
CREATE TABLE person (
id INTEGER PRIMARY KEY AUTOINCREMENT
UNIQUE
NOT NULL,
family VARCHAR (50),
name VARCHAR (50),
middlename VARCHAR (50),
dbirth DATE,
photo BLOB,
dateappend DATETIME,
prim TEXT
);
|
use cadastro;
#add coluna na tabela
alter table pessoas add column cursopreferido int;
#add chave estrangeira na coluna criada e referenciando outra tabela
alter table pessoas add foreign key (cursopreferido) references cursos(idcursos);
#atualizando cadastro adionando valor no novo campo com a chave primaria de outra tabela
update pessoas set cursopreferido = '5' where id = '1';
select nome, cursopreferido from pessoas;
#fazendo um INNER JOIN entre duas tabelas e trazendo resultados que as duas compartilham
select pessoas.nome, cursos.nome, cursos.ano from pessoas inner join cursos on cursos.idcursos = pessoas.cursopreferido;
#fazendo um LEFT OUTER JOIN trazendo os dados compartilhados e depois trazendo o restante da tabela da esquerda
select p.nome, c.nome, c.ano from pessoas as p left outer join cursos as c on c.idcursos = p.cursopreferido;
#fazendo um RIGHT OUTER JOIN trazendo os dados compartilhados e depois trazendo o restante da tabela da direita
select p.nome, c.nome, c.ano from pessoas as p right outer join cursos as c on c.idcursos = p.cursopreferido;
select * from cursos;
select * from pessoas;
describe cursos;
describe pessoas; |
select authors.au_id, authors.au_lname, authors.au_fname, titles.title, publishers.pub_name, Count(title) from authors
join titleauthor
on authors.au_id = titleauthor.au_id
join titles
on titles.title_id = titleauthor.title_id
join publishers
on titles.pub_id = publishers.pub_id
group by authors.au_id with rollup
order by Count(title) desc
limit 3; |
BEGIN
#Routine body goes here...
CALL deviceuserlog();
CALL deviceuserthreelog();
CALL deviceusersevenlog();
END
|
-- phpMyAdmin SQL Dump
-- version 3.4.11.1deb2+deb7u1
-- http://www.phpmyadmin.net
--
-- Client: localhost
-- Généré le: Jeu 19 Novembre 2015 à 11:44
-- Version du serveur: 5.5.44
-- Version de PHP: 5.4.41-0+deb7u1
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 données: `tp_espace_membres`
--
-- --------------------------------------------------------
--
-- Structure de la table `membres`
--
CREATE TABLE IF NOT EXISTS `membres` (
`ID_membre` int(11) NOT NULL AUTO_INCREMENT,
`pseudo` varchar(255) CHARACTER SET utf8 NOT NULL,
`pwd` varchar(255) CHARACTER SET utf8 NOT NULL,
`email` varchar(255) CHARACTER SET utf8 NOT NULL,
`date_inscription` date NOT NULL,
`actif` tinyint(1) NOT NULL,
PRIMARY KEY (`ID_membre`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
/*!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 */;
|
--
-- PostgreSQL database dump
--
-- Dumped from database version 9.6.6
-- Dumped by pg_dump version 9.6.6
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;
SET search_path = public, pg_catalog;
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: ex_app_risk_by_level; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE ex_app_risk_by_level (
id bigint NOT NULL,
ts timestamp with time zone NOT NULL,
low_risk integer,
mild_risk integer,
medium_risk integer,
high_risk integer,
critical_risk integer
);
ALTER TABLE ex_app_risk_by_level OWNER TO postgres;
--
-- Name: ex_app_risk_by_level_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE ex_app_risk_by_level_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE ex_app_risk_by_level_id_seq OWNER TO postgres;
--
-- Name: ex_app_risk_by_level_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE ex_app_risk_by_level_id_seq OWNED BY ex_app_risk_by_level.id;
--
-- Name: ex_governance_coverage; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE ex_governance_coverage (
id bigint NOT NULL,
ts timestamp with time zone NOT NULL,
users integer,
groups integer,
applications integer,
accounts integer,
permissions integer,
assignments integer
);
ALTER TABLE ex_governance_coverage OWNER TO postgres;
--
-- Name: ex_governance_coverage_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE ex_governance_coverage_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE ex_governance_coverage_id_seq OWNER TO postgres;
--
-- Name: ex_governance_coverage_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE ex_governance_coverage_id_seq OWNED BY ex_governance_coverage.id;
--
-- Name: ex_identity_lifecycle; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE ex_identity_lifecycle (
id bigint NOT NULL,
ts timestamp with time zone NOT NULL,
joiners integer,
leavers integer,
profilechanges integer
);
ALTER TABLE ex_identity_lifecycle OWNER TO postgres;
--
-- Name: ex_identity_lifecycle_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE ex_identity_lifecycle_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE ex_identity_lifecycle_id_seq OWNER TO postgres;
--
-- Name: ex_identity_lifecycle_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE ex_identity_lifecycle_id_seq OWNED BY ex_identity_lifecycle.id;
--
-- Name: ex_joiners_by_location; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE ex_joiners_by_location (
id bigint NOT NULL,
ts timestamp with time zone NOT NULL,
joiners integer,
location text
);
ALTER TABLE ex_joiners_by_location OWNER TO postgres;
--
-- Name: ex_joiners_by_location_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE ex_joiners_by_location_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE ex_joiners_by_location_id_seq OWNER TO postgres;
--
-- Name: ex_joiners_by_location_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE ex_joiners_by_location_id_seq OWNED BY ex_joiners_by_location.id;
--
-- Name: ex_leavers_by_location; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE ex_leavers_by_location (
id bigint NOT NULL,
ts timestamp with time zone NOT NULL,
leavers integer,
location text
);
ALTER TABLE ex_leavers_by_location OWNER TO postgres;
--
-- Name: ex_leavers_by_location_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE ex_leavers_by_location_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE ex_leavers_by_location_id_seq OWNER TO postgres;
--
-- Name: ex_leavers_by_location_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE ex_leavers_by_location_id_seq OWNED BY ex_leavers_by_location.id;
--
-- Name: ex_user_risk_by_level; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE ex_user_risk_by_level (
id bigint NOT NULL,
ts timestamp with time zone NOT NULL,
lowrisk integer,
mildrisk integer,
mediumrisk integer,
highrisk integer,
criticalrisk integer
);
ALTER TABLE ex_user_risk_by_level OWNER TO postgres;
--
-- Name: ex_user_risk_by_level_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE ex_user_risk_by_level_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE ex_user_risk_by_level_id_seq OWNER TO postgres;
--
-- Name: ex_user_risk_by_level_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE ex_user_risk_by_level_id_seq OWNED BY ex_user_risk_by_level.id;
--
-- Name: ex_app_risk_by_level id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY ex_app_risk_by_level ALTER COLUMN id SET DEFAULT nextval('ex_app_risk_by_level_id_seq'::regclass);
--
-- Name: ex_governance_coverage id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY ex_governance_coverage ALTER COLUMN id SET DEFAULT nextval('ex_governance_coverage_id_seq'::regclass);
--
-- Name: ex_identity_lifecycle id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY ex_identity_lifecycle ALTER COLUMN id SET DEFAULT nextval('ex_identity_lifecycle_id_seq'::regclass);
--
-- Name: ex_joiners_by_location id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY ex_joiners_by_location ALTER COLUMN id SET DEFAULT nextval('ex_joiners_by_location_id_seq'::regclass);
--
-- Name: ex_leavers_by_location id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY ex_leavers_by_location ALTER COLUMN id SET DEFAULT nextval('ex_leavers_by_location_id_seq'::regclass);
--
-- Name: ex_user_risk_by_level id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY ex_user_risk_by_level ALTER COLUMN id SET DEFAULT nextval('ex_user_risk_by_level_id_seq'::regclass);
--
-- Data for Name: ex_app_risk_by_level; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY ex_app_risk_by_level (id, ts, low_risk, mild_risk, medium_risk, high_risk, critical_risk) FROM stdin;
1 2018-06-14 11:39:41.723-04 0 0 0 0 0
2 2018-06-14 12:19:32.704-04 0 0 0 0 0
3 2018-06-14 12:21:30.22-04 0 0 0 0 0
4 2018-06-14 12:28:26.509-04 0 0 0 0 0
5 2018-06-14 12:38:40.183-04 0 0 0 0 0
6 2018-06-14 12:51:59.125-04 1 0 0 0 0
7 2018-06-14 12:57:29.921-04 0 0 0 1 0
8 2018-06-14 13:14:18.506-04 0 0 0 1 0
9 2018-06-15 10:13:24.746-04 0 0 0 1 0
10 2018-06-18 10:27:44.683-04 0 0 0 1 0
11 2018-06-18 11:34:39.368-04 0 0 0 1 0
12 2018-06-18 11:41:54.438-04 0 0 0 1 0
13 2018-06-18 15:32:13.311-04 1 1 0 1 1
14 2018-06-19 15:44:31.17-04 1 1 0 1 1
\.
--
-- Name: ex_app_risk_by_level_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('ex_app_risk_by_level_id_seq', 14, true);
update ex_app_risk_by_level set ts = ts + (select now() - max(f.ts) from ex_app_risk_by_level f);
--
-- Data for Name: ex_governance_coverage; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY ex_governance_coverage (id, ts, users, groups, applications, accounts, permissions, assignments) FROM stdin;
1 2018-06-14 11:39:41.387-04 0 0 0 0 0 0
2 2018-06-14 12:21:30.241-04 0 0 0 0 0 0
3 2018-06-14 12:28:26.533-04 70 22 0 0 0 0
4 2018-06-14 12:38:40.204-04 971 32 0 0 0 0
5 2018-06-14 12:51:59.146-04 971 32 1 0 0 0
6 2018-06-14 12:57:29.942-04 971 32 1 540 13 93
7 2018-06-14 13:14:18.539-04 971 32 1 540 13 93
8 2018-06-15 10:13:24.831-04 971 32 1 540 13 93
9 2018-06-18 10:27:44.164-04 971 32 1 540 13 93
10 2018-06-18 11:34:39.393-04 973 32 1 540 13 93
11 2018-06-18 11:41:54.463-04 973 32 1 540 13 93
12 2018-06-18 15:11:25.718-04 973 32 3 540 41 431
13 2018-06-18 15:17:22.673-04 973 32 4 540 97 3941
14 2018-06-18 15:32:13.673-04 973 32 4 540 176 5239
15 2018-06-19 15:44:30.531-04 973 32 4 540 176 5239
\.
update ex_governance_coverage set ts = ts + (select now() - max(f.ts) from ex_governance_coverage f);
--
-- Name: ex_governance_coverage_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('ex_governance_coverage_id_seq', 15, true);
--
-- Data for Name: ex_identity_lifecycle; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY ex_identity_lifecycle (id, ts, joiners, leavers, profilechanges) FROM stdin;
1 2018-06-14 11:39:41.758-04 0 0 0
2 2018-06-14 12:19:32.724-04 0 0 0
3 2018-06-14 12:21:30.256-04 0 0 0
4 2018-06-14 12:28:26.551-04 70 0 0
5 2018-06-14 12:38:40.224-04 971 0 15
6 2018-06-14 12:51:59.165-04 971 0 15
7 2018-06-14 12:57:29.964-04 971 0 986
8 2018-06-14 13:14:18.56-04 971 0 986
9 2018-06-15 10:13:24.885-04 971 10 986
10 2018-06-18 10:27:44.727-04 0 0 0
11 2018-06-18 11:34:39.407-04 2 0 2
12 2018-06-18 11:41:54.481-04 2 5 2
13 2018-06-19 15:44:31.219-04 2 0 975
\.
update ex_identity_lifecycle set ts = ts + (select now() - max(f.ts) from ex_identity_lifecycle f);
--
-- Name: ex_identity_lifecycle_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('ex_identity_lifecycle_id_seq', 13, true);
--
-- Data for Name: ex_joiners_by_location; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY ex_joiners_by_location (id, ts, joiners, location) FROM stdin;
1 2018-06-14 12:28:26.57-04 70 \N
2 2018-06-14 12:38:40.247-04 299 Boston
3 2018-06-14 12:38:40.247-04 62 \N
4 2018-06-14 12:38:40.247-04 30 Houston
5 2018-06-14 12:38:40.247-04 151 Las Vegas
6 2018-06-14 12:38:40.247-04 74 New York
7 2018-06-14 12:38:40.247-04 168 San Francisco
8 2018-06-14 12:38:40.247-04 187 Chicago
9 2018-06-14 12:51:59.184-04 299 Boston
10 2018-06-14 12:51:59.184-04 62 \N
11 2018-06-14 12:51:59.184-04 30 Houston
12 2018-06-14 12:51:59.184-04 151 Las Vegas
13 2018-06-14 12:51:59.184-04 74 New York
14 2018-06-14 12:51:59.184-04 168 San Francisco
15 2018-06-14 12:51:59.184-04 187 Chicago
16 2018-06-14 12:57:29.985-04 299 Boston
17 2018-06-14 12:57:29.985-04 62 \N
18 2018-06-14 12:57:29.985-04 30 Houston
19 2018-06-14 12:57:29.985-04 74 New York
20 2018-06-14 12:57:29.985-04 151 Las Vegas
21 2018-06-14 12:57:29.985-04 168 San Francisco
22 2018-06-14 12:57:29.985-04 187 Chicago
23 2018-06-14 13:14:18.578-04 299 Boston
24 2018-06-14 13:14:18.578-04 62 \N
25 2018-06-14 13:14:18.578-04 30 Houston
26 2018-06-14 13:14:18.578-04 74 New York
27 2018-06-14 13:14:18.578-04 151 Las Vegas
28 2018-06-14 13:14:18.578-04 168 San Francisco
29 2018-06-14 13:14:18.578-04 187 Chicago
30 2018-06-14 15:30:47.171-04 299 Boston
31 2018-06-14 15:30:47.171-04 62 \N
32 2018-06-14 15:30:47.171-04 30 Houston
33 2018-06-14 15:30:47.171-04 74 New York
34 2018-06-14 15:30:47.171-04 151 Las Vegas
35 2018-06-14 15:30:47.171-04 168 San Francisco
36 2018-06-14 15:30:47.171-04 187 Chicago
37 2018-06-14 16:30:08.663-04 299 Boston
38 2018-06-14 16:30:08.663-04 62 \N
39 2018-06-14 16:30:08.663-04 30 Houston
40 2018-06-14 16:30:08.663-04 74 New York
41 2018-06-14 16:30:08.663-04 151 Las Vegas
42 2018-06-14 16:30:08.663-04 168 San Francisco
43 2018-06-14 16:30:08.663-04 187 Chicago
44 2018-06-15 10:13:24.919-04 299 Boston
45 2018-06-15 10:13:24.919-04 62 \N
46 2018-06-15 10:13:24.919-04 30 Houston
47 2018-06-15 10:13:24.919-04 74 New York
48 2018-06-15 10:13:24.919-04 151 Las Vegas
49 2018-06-15 10:13:24.919-04 168 San Francisco
50 2018-06-15 10:13:24.919-04 187 Chicago
51 2018-06-18 11:34:39.422-04 1 Boston
52 2018-06-18 11:34:39.422-04 1 Cambridge
53 2018-06-18 11:41:54.497-04 1 Boston
54 2018-06-18 11:41:54.497-04 1 Cambridge
55 2018-06-19 15:44:31.5-04 1 Boston
56 2018-06-19 15:44:31.5-04 1 Cambridge
\.
update ex_joiners_by_location set ts = ts + (select now() - max(f.ts) from ex_joiners_by_location f);
--
-- Name: ex_joiners_by_location_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('ex_joiners_by_location_id_seq', 56, true);
--
-- Data for Name: ex_leavers_by_location; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY ex_leavers_by_location (id, ts, leavers, location) FROM stdin;
1 2018-06-15 11:08:04.522951-04 10 Chicago
2 2018-06-18 02:52:09.522951-04 5 New York
\.
update ex_leavers_by_location set ts = ts + (select now() - max(f.ts) from ex_leavers_by_location f);
--
-- Name: ex_leavers_by_location_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('ex_leavers_by_location_id_seq', 1, true);
--
-- Data for Name: ex_user_risk_by_level; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY ex_user_risk_by_level (id, ts, lowrisk, mildrisk, mediumrisk, highrisk, criticalrisk) FROM stdin;
1 2018-06-14 11:39:41.349-04 0 0 0 0 0
2 2018-06-14 12:19:32.787-04 0 0 0 0 0
3 2018-06-14 12:21:30.303-04 0 0 0 0 0
4 2018-06-14 12:28:26.606-04 70 0 0 0 0
5 2018-06-14 12:38:40.282-04 971 0 0 0 0
6 2018-06-14 12:51:59.226-04 971 0 0 0 0
7 2018-06-14 12:57:30.02-04 862 0 0 540 0
8 2018-06-14 13:14:18.616-04 862 0 0 540 0
9 2018-06-15 10:13:24.979-04 862 0 0 540 0
10 2018-06-18 10:27:43.899-04 862 0 0 540 0
11 2018-06-18 11:34:39.456-04 1295 0 0 540 0
12 2018-06-18 11:41:54.531-04 1295 0 0 540 0
13 2018-06-18 15:32:13.808-04 1289 510 4 30 0
14 2018-06-19 15:44:30.25-04 1289 510 4 30 0
\.
update ex_user_risk_by_level set ts = ts + (select now() - max(f.ts) from ex_user_risk_by_level f);
--
-- Name: ex_user_risk_by_level_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('ex_user_risk_by_level_id_seq', 14, true);
--
-- Name: ex_app_risk_by_level ex_app_risk_by_level_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY ex_app_risk_by_level
ADD CONSTRAINT ex_app_risk_by_level_pkey PRIMARY KEY (id);
--
-- Name: ex_governance_coverage ex_governance_coverage_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY ex_governance_coverage
ADD CONSTRAINT ex_governance_coverage_pkey PRIMARY KEY (id);
--
-- Name: ex_identity_lifecycle ex_identity_lifecycle_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY ex_identity_lifecycle
ADD CONSTRAINT ex_identity_lifecycle_pkey PRIMARY KEY (id);
--
-- Name: ex_joiners_by_location ex_joiners_by_location_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY ex_joiners_by_location
ADD CONSTRAINT ex_joiners_by_location_pkey PRIMARY KEY (id);
--
-- Name: ex_leavers_by_location ex_leavers_by_location_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY ex_leavers_by_location
ADD CONSTRAINT ex_leavers_by_location_pkey PRIMARY KEY (id);
--
-- Name: ex_user_risk_by_level ex_user_risk_by_level_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY ex_user_risk_by_level
ADD CONSTRAINT ex_user_risk_by_level_pkey PRIMARY KEY (id);
--
-- PostgreSQL database dump complete
--
|
CREATE VIEW DepartmentEmployeeCount_View AS
SELECT d.department_name 'DEPARTMENT', COUNT(e.employee_id) '# of Employees'
FROM rob.departments d JOIN rob.employees e
ON d.department_id = e.department_id
GROUP BY department_id
ORDER BY d.department_name; |
alter table decisions drop column voting_planned_opening_date;
alter table decisions change voting_planned_closing_date planned_closing_date datetime not null;
alter table decisions change voting_actual_closing_date actual_closing_date datetime;
alter table decisions add index (actual_closing_date);
|
-- Initial public schema relates to Library 0.x
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA pg_catalog;
SET search_path = public, pg_catalog;
SET default_tablespace = '';
-- report
CREATE TABLE report (
report_id uuid NOT NULL DEFAULT uuid_generate_v1mc(),
book_id uuid NOT NULL,
report_date timestamp with time zone NOT NULL DEFAULT now(),
CONSTRAINT report_pk PRIMARY KEY (report_id)
);
CREATE INDEX report_report_date
ON report (report_date);
|
/*
Navicat MySQL Data Transfer
Source Server : 127.0.0.1_3306
Source Server Version : 50718
Source Host : 127.0.0.1:3306
Source Database : logistics
Target Server Type : MYSQL
Target Server Version : 50718
File Encoding : 65001
Date: 2018-11-20 09:41:35
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for path
-- ----------------------------
DROP TABLE IF EXISTS `path`;
CREATE TABLE `path` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '路线id',
`startplace` varchar(11) NOT NULL COMMENT '起始地',
`endplace` varchar(11) NOT NULL COMMENT '终止地',
`priceperunit` double DEFAULT NULL COMMENT '单价',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of path
-- ----------------------------
INSERT INTO `path` VALUES ('1', '襄樊', '保康', '20.1');
INSERT INTO `path` VALUES ('2', '襄阳', '鄂州', '30.5');
INSERT INTO `path` VALUES ('3', '宜城', '孝感', '40.5');
INSERT INTO `path` VALUES ('4', '南漳', '大悟', '50.2');
INSERT INTO `path` VALUES ('5', '谷城', '汉川', '60.2');
|
/*
执行用时:380 ms, 在所有 MySQL 提交中击败了72.04% 的用户
内存消耗:0 B, 在所有 MySQL 提交中击败了100.00% 的用户
通过测试用例:14 / 14
*/
# Write your MySQL query statement below
select e1.Name as Employee
from Employee e1, Employee e2
where e1.ManagerId = e2.Id and e1.Salary > e2.Salary
/*
join
执行用时:403 ms, 在所有 MySQL 提交中击败了39.90% 的用户
内存消耗:0 B, 在所有 MySQL 提交中击败了100.00% 的用户
通过测试用例:14 / 14
*/
# Write your MySQL query statement below
select e1.Name as Employee
from Employee e1
join Employee e2
on e1.ManagerId = e2.Id and e1.Salary > e2.Salary
/*
left join
执行用时:374 ms, 在所有 MySQL 提交中击败了85.03% 的用户
内存消耗:0 B, 在所有 MySQL 提交中击败了100.00% 的用户
通过测试用例:14 / 14
*/
# Write your MySQL query statement below
select e1.Name as Employee
from Employee e1
left join Employee e2
on e1.ManagerId = e2.Id
where e1.Salary > e2.Salary
/*
inner join
执行用时:388 ms, 在所有 MySQL 提交中击败了57.27% 的用户
内存消耗:0 B, 在所有 MySQL 提交中击败了100.00% 的用户
通过测试用例:14 / 14
*/
# Write your MySQL query statement below
select e1.Name as Employee
from Employee e1
inner join Employee e2
on e1.ManagerId = e2.Id and e1.Salary > e2.Salary
/*
right join
执行用时:519 ms, 在所有 MySQL 提交中击败了12.73% 的用户
内存消耗:0 B, 在所有 MySQL 提交中击败了100.00% 的用户
通过测试用例:14 / 14
*/
# Write your MySQL query statement below
select e1.Name as Employee
from Employee e1
right join Employee e2
on e1.ManagerId = e2.Id
where e1.Salary > e2.Salary
/*
执行用时:1226 ms, 在所有 MySQL 提交中击败了5.02% 的用户
内存消耗:0 B, 在所有 MySQL 提交中击败了100.00% 的用户
通过测试用例:14 / 14
*/
# Write your MySQL query statement below
select e.Name as Employee
from Employee e
where salary > (select salary from Employee where id = e.ManagerId)
|
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema Libreria
-- -----------------------------------------------------
-- Base de datos para una Libreria Web
-- -----------------------------------------------------
-- Schema Libreria
--
-- Base de datos para una Libreria Web
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `Libreria` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `Libreria` ;
-- -----------------------------------------------------
-- Table `Libreria`.`Editorial`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Libreria`.`Editorial` (
`IdEditorial` INT NOT NULL,
`Nombre` VARCHAR(50) NULL,
`Telefono` MEDIUMTEXT NULL,
`ContactoPersona` VARCHAR(50) NULL,
`Direccion` VARCHAR(100) NULL,
`Ciudad` VARCHAR(50) NULL,
PRIMARY KEY (`IdEditorial`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Libreria`.`Tema`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Libreria`.`Tema` (
`IdTema` INT NOT NULL,
`Nombre` VARCHAR(50) NULL,
PRIMARY KEY (`IdTema`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Libreria`.`Libro`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Libreria`.`Libro` (
`idLibro` INT NOT NULL,
`Titulo` VARCHAR(45) NULL,
`NumPagina` INT NULL,
`NumEdicion` INT NULL,
`TipoCubierta` VARCHAR(20) NULL,
`Idioma` VARCHAR(45) NULL,
`Precio` FLOAT NULL,
`IdEditorial` INT NULL,
`IdTema` INT NULL,
PRIMARY KEY (`idLibro`),
INDEX `IdEditorial_idx` (`IdEditorial` ASC),
INDEX `IdTema_idx` (`IdTema` ASC),
CONSTRAINT `IdEditorial1`
FOREIGN KEY (`IdEditorial`)
REFERENCES `Libreria`.`Editorial` (`IdEditorial`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `IdTema`
FOREIGN KEY (`IdTema`)
REFERENCES `Libreria`.`Tema` (`IdTema`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Libreria`.`Autor`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Libreria`.`Autor` (
`IdAutor` INT NOT NULL,
`Nombre` VARCHAR(45) NULL,
`Apellido` VARCHAR(45) NULL,
`Pais` VARCHAR(45) NULL,
PRIMARY KEY (`IdAutor`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Libreria`.`Ejemplar`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Libreria`.`Ejemplar` (
`IdLibro` INT NOT NULL,
`IdAutor` INT NOT NULL,
`Cantidad` INT NULL,
`NumEstante` INT NULL,
PRIMARY KEY (`IdLibro`, `IdAutor`),
INDEX `IdAutor_idx` (`IdAutor` ASC),
CONSTRAINT `IdAutor2`
FOREIGN KEY (`IdAutor`)
REFERENCES `Libreria`.`Autor` (`IdAutor`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `IdLibro`
FOREIGN KEY (`IdLibro`)
REFERENCES `Libreria`.`Libro` (`idLibro`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Libreria`.`Cliente`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Libreria`.`Cliente` (
`IdCliente` INT NOT NULL,
`Nombre` VARCHAR(45) NULL,
`Apellido` VARCHAR(45) NULL,
`Cedula` MEDIUMTEXT NULL,
`Telefono` MEDIUMTEXT NULL,
`Direccion` VARCHAR(100) NULL,
`Correo` VARCHAR(50) NULL,
`Contraseña` MEDIUMTEXT NULL,
PRIMARY KEY (`IdCliente`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Libreria`.`Pedido`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Libreria`.`Pedido` (
`IdPedido` INT NOT NULL,
`Fecha` DATETIME NULL,
`NumTarjeta` MEDIUMTEXT NULL,
`IdCliente` INT NULL,
PRIMARY KEY (`IdPedido`),
INDEX `IdCliente_idx` (`IdCliente` ASC),
CONSTRAINT `IdCliente3`
FOREIGN KEY (`IdCliente`)
REFERENCES `Libreria`.`Cliente` (`IdCliente`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Libreria`.`Pedido Cliente`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Libreria`.`Pedido Cliente` (
`IdLibro` INT NOT NULL,
`IdPedido` INT NOT NULL,
`Cantidad` INT NULL,
`Precio` FLOAT NULL,
PRIMARY KEY (`IdLibro`, `IdPedido`),
INDEX `IdPedido_idx` (`IdPedido` ASC),
CONSTRAINT `IdLibro4`
FOREIGN KEY (`IdLibro`)
REFERENCES `Libreria`.`Libro` (`idLibro`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `IdPedido`
FOREIGN KEY (`IdPedido`)
REFERENCES `Libreria`.`Pedido` (`IdPedido`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Libreria`.`Proveedor`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Libreria`.`Proveedor` (
`IdProveedor` INT NOT NULL,
`Nombre` VARCHAR(45) NULL,
`Apellido` VARCHAR(45) NULL,
`Telefono` MEDIUMTEXT NULL,
`Direccion` VARCHAR(100) NULL,
`Correo` VARCHAR(50) NULL,
PRIMARY KEY (`IdProveedor`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Libreria`.`Suministro`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Libreria`.`Suministro` (
`IdProveedor` INT NOT NULL,
`IdLibro` INT NOT NULL,
`Cantidad` INT NULL,
`Precio` FLOAT NULL,
INDEX `IdProveedor_idx` (`IdProveedor` ASC),
INDEX `IdLibro_idx` (`IdLibro` ASC),
PRIMARY KEY (`IdProveedor`, `IdLibro`),
CONSTRAINT `IdProveedor5`
FOREIGN KEY (`IdProveedor`)
REFERENCES `Libreria`.`Proveedor` (`IdProveedor`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `IdLibro12`
FOREIGN KEY (`IdLibro`)
REFERENCES `Libreria`.`Libro` (`idLibro`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Libreria`.`Foto`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Libreria`.`Foto` (
`IdLibro` INT NULL,
`Imagen` LONGBLOB NULL,
INDEX `IdLibro_idx` (`IdLibro` ASC),
CONSTRAINT `IdLibro6`
FOREIGN KEY (`IdLibro`)
REFERENCES `Libreria`.`Libro` (`idLibro`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
USE `Libreria` ;
-- -----------------------------------------------------
-- Placeholder table for view `Libreria`.`view1`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Libreria`.`view1` (`id` INT);
-- -----------------------------------------------------
-- View `Libreria`.`view1`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Libreria`.`view1`;
USE `Libreria`;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
/*
//vista creada por mi
USE `Libreria` ;
create view Autores
as
(
select nombre
,apellido
from autor
);
*/
|
create or replace package npg_demo_sub
as
/** A dependent package in a subdirectory
* @author Morten Egan
* @version 0.0.1
* @project NPG Demo
*/
npg_version varchar2(250) := '0.0.1';
/** A dummy procedure with bla
* @author Morten Egan
* @param param_name The description of the parameter
*/
procedure a_dummy_procedure;
end npg_demo_sub;
/
|
USE gpr;
INSERT INTO Producto ( IdProducto, Nombre, FechaRegistro, IdEstado)
VALUES
( 1, 'Enfrijoladas', N'2003-11-01T00:00:00', 1 ),
( 2, 'Sopa de tortilla', N'2000-09-18T00:00:00', 2 ),
( 3, 'Frijoles refritos', N'2002-03-16T00:00:00', 3 ),
( 4, 'Chilaquiles', N'2004-01-28T00:00:00', 4 ),
( 5, 'Tamales', N'2005-06-10T00:00:00', 5 ),
( 6, 'Tostadas', N'2002-03-21T00:00:00', 6 ),
( 7, 'Sopa de tortilla', N'2002-04-05T00:00:00', 7 ),
( 8, 'Picadillo', N'2001-12-14T00:00:00', 8 ),
( 9, 'Frijoles refritos', N'2005-09-12T00:00:00', 9 ),
( 10, 'Tostadas', N'2006-07-24T00:00:00', 10 ),
( 11, 'Mole poblano', N'2000-06-29T00:00:00', 11 ),
( 12, 'Pozole', N'2005-02-17T00:00:00', 12 ),
( 13, 'Pozole', N'2004-11-07T00:00:00', 13 ),
( 14, 'Pozole', N'2003-07-13T00:00:00', 14 ); |
SELECT DISTINCT name
FROM Movies
INNER JOIN Rating USING(mID)
INNER JOIN Reviewer USING(rID)
WHERE title = 'Gone with the Wind' |
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50714
Source Host : 127.0.0.1:3306
Source Database : kiliexpress
Target Server Type : MYSQL
Target Server Version : 50714
File Encoding : 65001
Date: 2017-07-03 14:28:54
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for admin_menu
-- ----------------------------
DROP TABLE IF EXISTS `admin_menu`;
CREATE TABLE `admin_menu` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`parent_id` int(11) NOT NULL DEFAULT '0',
`order` int(11) NOT NULL DEFAULT '0',
`title` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`icon` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`uri` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for admin_operation_log
-- ----------------------------
DROP TABLE IF EXISTS `admin_operation_log`;
CREATE TABLE `admin_operation_log` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`path` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`method` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL,
`ip` varchar(15) COLLATE utf8mb4_unicode_ci NOT NULL,
`input` text COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `admin_operation_log_user_id_index` (`user_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1570 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for admin_permissions
-- ----------------------------
DROP TABLE IF EXISTS `admin_permissions`;
CREATE TABLE `admin_permissions` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
`slug` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `admin_permissions_name_unique` (`name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for admin_roles
-- ----------------------------
DROP TABLE IF EXISTS `admin_roles`;
CREATE TABLE `admin_roles` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
`slug` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `admin_roles_name_unique` (`name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for admin_role_menu
-- ----------------------------
DROP TABLE IF EXISTS `admin_role_menu`;
CREATE TABLE `admin_role_menu` (
`role_id` int(11) NOT NULL DEFAULT '0',
`menu_id` int(11) NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
KEY `admin_role_menu_role_id_menu_id_index` (`role_id`,`menu_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for admin_role_permissions
-- ----------------------------
DROP TABLE IF EXISTS `admin_role_permissions`;
CREATE TABLE `admin_role_permissions` (
`role_id` int(11) NOT NULL DEFAULT '0',
`permission_id` int(11) NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
KEY `admin_role_permissions_role_id_permission_id_index` (`role_id`,`permission_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for admin_role_users
-- ----------------------------
DROP TABLE IF EXISTS `admin_role_users`;
CREATE TABLE `admin_role_users` (
`role_id` int(11) NOT NULL DEFAULT '0',
`user_id` int(11) NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
KEY `admin_role_users_role_id_user_id_index` (`role_id`,`user_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for admin_users
-- ----------------------------
DROP TABLE IF EXISTS `admin_users`;
CREATE TABLE `admin_users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(190) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`avatar` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `admin_users_username_unique` (`username`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for admin_user_permissions
-- ----------------------------
DROP TABLE IF EXISTS `admin_user_permissions`;
CREATE TABLE `admin_user_permissions` (
`user_id` int(11) NOT NULL DEFAULT '0',
`permission_id` int(11) NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
KEY `admin_user_permissions_user_id_permission_id_index` (`user_id`,`permission_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for jobs
-- ----------------------------
DROP TABLE IF EXISTS `jobs`;
CREATE TABLE `jobs` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`queue` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`attempts` tinyint(3) unsigned NOT NULL,
`reserved_at` int(10) unsigned DEFAULT NULL,
`available_at` int(10) unsigned NOT NULL,
`created_at` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for kili_apilog
-- ----------------------------
DROP TABLE IF EXISTS `kili_apilog`;
CREATE TABLE `kili_apilog` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增主键',
`data` text COMMENT '通知或请求数据',
`type` tinyint(1) NOT NULL DEFAULT '1' COMMENT '类型:1接收到通知 2发出去数据 ',
`sign` varchar(255) NOT NULL COMMENT '签名',
`add_time` int(11) NOT NULL DEFAULT '0' COMMENT '添加时间',
`url` varchar(200) DEFAULT NULL COMMENT '接口地址',
`return` text COMMENT '返回结果',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1630 DEFAULT CHARSET=utf8 COMMENT='接收到的notice请求';
-- ----------------------------
-- Table structure for kili_apiurl
-- ----------------------------
DROP TABLE IF EXISTS `kili_apiurl`;
CREATE TABLE `kili_apiurl` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`manager_id` int(11) NOT NULL,
`type_id` tinyint(1) NOT NULL COMMENT '类型,',
`url` varchar(255) DEFAULT NULL,
`remark` varchar(255) DEFAULT NULL COMMENT '说明',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_clients
-- ----------------------------
DROP TABLE IF EXISTS `kili_clients`;
CREATE TABLE `kili_clients` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(20) NOT NULL DEFAULT '' COMMENT ' 商家名称',
`contact_person` varchar(50) DEFAULT '' COMMENT '联系人',
`phone` varchar(50) NOT NULL COMMENT '联系电话',
`app_key` varchar(30) NOT NULL COMMENT '调用api的appkey',
`app_secret` varchar(50) DEFAULT NULL COMMENT 'api加密字符串,限制为16位,后续可升级',
`addtime` int(11) NOT NULL DEFAULT '0' COMMENT '添加时间',
`short_name` varchar(2) NOT NULL COMMENT '用',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_clients_apiurl
-- ----------------------------
DROP TABLE IF EXISTS `kili_clients_apiurl`;
CREATE TABLE `kili_clients_apiurl` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`client_id` int(11) NOT NULL COMMENT '用户id',
`url` varchar(255) NOT NULL,
`remark` varchar(255) DEFAULT NULL COMMENT '说明',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`type` varchar(25) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_clients_merchants
-- ----------------------------
DROP TABLE IF EXISTS `kili_clients_merchants`;
CREATE TABLE `kili_clients_merchants` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(20) NOT NULL DEFAULT '' COMMENT ' 商家名称',
`client_id` varchar(255) DEFAULT NULL COMMENT '所属客户',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_cost_records
-- ----------------------------
DROP TABLE IF EXISTS `kili_cost_records`;
CREATE TABLE `kili_cost_records` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`money` double(8,2) NOT NULL COMMENT '扣款金额',
`date` date NOT NULL COMMENT '扣款的时间',
`remark` text COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for kili_country
-- ----------------------------
DROP TABLE IF EXISTS `kili_country`;
CREATE TABLE `kili_country` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) DEFAULT NULL COMMENT '发往国家名称',
`code` varchar(10) DEFAULT NULL COMMENT '国家二字代码',
`is_dms` int(11) DEFAULT NULL,
`shipping_method_id` int(6) NOT NULL COMMENT '配送方式表主键id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_couriers
-- ----------------------------
DROP TABLE IF EXISTS `kili_couriers`;
CREATE TABLE `kili_couriers` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增主键',
`courier_name` varchar(255) NOT NULL DEFAULT '' COMMENT '快递公司名',
`phone` varchar(50) NOT NULL COMMENT '联系电话,因为格式不确定,所以用字符串格式',
`address` varchar(255) NOT NULL COMMENT '公司地址',
`user` varchar(255) NOT NULL DEFAULT '' COMMENT '快递公司联系人员',
`app_key` varchar(255) NOT NULL DEFAULT '' COMMENT '加密字段,用于效验接口',
`app_secret` varchar(255) DEFAULT NULL,
`type` tinyint(1) NOT NULL DEFAULT '0' COMMENT '类型',
`country_id` int(11) DEFAULT NULL,
`payment_code` varchar(255) NOT NULL COMMENT '快递公司支付账户',
`need_waybill` tinyint(1) DEFAULT '1' COMMENT '是否需要生成快递单号,默认需要',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='快递公司名';
-- ----------------------------
-- Table structure for kili_couriers_apiurl
-- ----------------------------
DROP TABLE IF EXISTS `kili_couriers_apiurl`;
CREATE TABLE `kili_couriers_apiurl` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`courier_id` int(11) NOT NULL DEFAULT '0' COMMENT '快递公司id,与客户id两个比填一个',
`url` varchar(255) NOT NULL,
`remark` varchar(255) DEFAULT '' COMMENT '说明',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`type` varchar(50) NOT NULL DEFAULT '' COMMENT 'url类型\r\n1gs订单是否可以取消\r\n2取消gs订单\r\n3ds订单是否可以取消\r\n4取消ds订单\r\n5中转仓下发\r\n6通知bbc取消订单',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_deduction
-- ----------------------------
DROP TABLE IF EXISTS `kili_deduction`;
CREATE TABLE `kili_deduction` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL DEFAULT '0' COMMENT '用户ID',
`amount` float(11,5) NOT NULL DEFAULT '0.00000' COMMENT '金额',
`store_id` int(11) NOT NULL COMMENT '店铺id分类表',
`store_name` varchar(255) NOT NULL DEFAULT '',
`date` date DEFAULT NULL COMMENT '日期',
`week` varchar(11) NOT NULL DEFAULT '0' COMMENT '多少周',
`month` varchar(11) NOT NULL DEFAULT '0' COMMENT '每月总计。。但date_type 为3 才显示',
`charge_type` tinyint(1) NOT NULL COMMENT '同freight money_type',
`money_type` tinyint(1) NOT NULL COMMENT '同freight money_type',
`is_paid` tinyint(1) NOT NULL DEFAULT '0' COMMENT '此批次金额是否扣除 0 未 1扣除',
`date_type` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1 每天 2 每周 3每月',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=485 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_freight
-- ----------------------------
DROP TABLE IF EXISTS `kili_freight`;
CREATE TABLE `kili_freight` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '支付方向',
`charge_type` varchar(255) NOT NULL COMMENT '计费大类,包括:物流头程段0、海外仓储段1、尾程配送段2',
`money_type` varchar(255) NOT NULL COMMENT '费用类型,头程包括:1 空运费 , 2海运费;仓储包括:0收货上架费、1库内操作费 、2库内仓储费、3退货处理费、4 返厂处理费;尾程包括:配送费、揽收费',
`factor1` varchar(255) NOT NULL COMMENT '计费因子1:头程|:目的国;仓库:商品分类;尾程:城市',
`factor2` varchar(255) NOT NULL COMMENT '计费因子2,头程:物流渠道(1 赛拾、2天龙 3有马);仓库:首件/单、续件/单;尾程:首重/续重',
`factor3` varchar(255) DEFAULT NULL COMMENT '计费因子3:备用',
`factor4` varchar(255) DEFAULT NULL COMMENT '计费因子4:备用',
`factor5` varchar(255) DEFAULT NULL COMMENT '计费因子5:备用',
`factor6` varchar(255) DEFAULT NULL COMMENT '计费因子6:备用',
`factor7` varchar(255) DEFAULT NULL COMMENT '计费因子7:备用',
`factor8` varchar(255) DEFAULT NULL COMMENT '计费因子8:备用',
`factor9` varchar(255) DEFAULT NULL COMMENT '计费因子9:备用',
`factor10` varchar(255) DEFAULT NULL COMMENT '计费因子10:备用',
`rate` float(12,4) NOT NULL COMMENT '费率',
`order_sn` varchar(20) NOT NULL DEFAULT '' COMMENT '平台订单号',
`store_id` int(11) NOT NULL DEFAULT '0' COMMENT '商家id',
`type_id` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1 肯尼亚 2尼日利亚 3乌干达',
`receivable_money` decimal(10,5) NOT NULL DEFAULT '0.00000' COMMENT '应收金额',
`real_money` decimal(10,5) NOT NULL DEFAULT '0.00000' COMMENT '实收金额',
`payable_money` decimal(10,5) NOT NULL DEFAULT '0.00000',
`paid_money` decimal(10,5) NOT NULL DEFAULT '0.00000' COMMENT '实际支付金额',
`pay_direct` tinyint(1) NOT NULL DEFAULT '0' COMMENT '交易方向:0 应收 1 应付',
`pay_type` varchar(5) NOT NULL DEFAULT '' COMMENT '交易类型 预付充值、扣款、转账',
`biz_status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '交易状态',
`settlement_status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '结算状态',
`is_paid` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否支付 0 未支付 1支付',
`account` varchar(255) NOT NULL DEFAULT '' COMMENT '支付账户',
`transit_id` varchar(20) NOT NULL DEFAULT '' COMMENT '交易流水号',
`add_time` int(11) NOT NULL DEFAULT '0',
`pay_time` int(11) NOT NULL DEFAULT '0' COMMENT '流水时间',
`servicer_id` int(11) NOT NULL DEFAULT '0',
`waybill_number` varchar(20) NOT NULL DEFAULT '',
`city` varchar(255) NOT NULL COMMENT '城市',
`weight` double(10,2) NOT NULL COMMENT '重量',
`date` date NOT NULL,
`class_id` int(3) NOT NULL,
`store_name` varchar(255) NOT NULL DEFAULT '' COMMENT '店铺名',
`quantity` int(11) NOT NULL COMMENT '数量',
`sku_id` varchar(20) NOT NULL COMMENT 'sku,为DMS、WMS上传的系统',
`goods_id` int(11) NOT NULL DEFAULT '0',
`pay_user_id` int(11) NOT NULL DEFAULT '0' COMMENT '当时扣款所属的用户ID,非创建时d的ID。(主要用于创建店铺更改用户时的情况)',
`update_time` int(11) NOT NULL DEFAULT '0',
`admin_user_id` int(11) NOT NULL DEFAULT '0' COMMENT '管理员用户id',
`user_id` int(11) NOT NULL DEFAULT '0' COMMENT '用户ID',
`index` varchar(20) NOT NULL DEFAULT '0' COMMENT '用于区分是否多次传输次数',
`seller_id` int(11) NOT NULL DEFAULT '0' COMMENT 'kili_sellers 表的主键,不是wms、dms推送过来的seller_id,seller_id 可以根据store_id,type_id 推算出',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1881 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_freight_0622_2
-- ----------------------------
DROP TABLE IF EXISTS `kili_freight_0622_2`;
CREATE TABLE `kili_freight_0622_2` (
`id` int(11) NOT NULL DEFAULT '0' COMMENT '支付方向',
`charge_type` varchar(255) NOT NULL COMMENT '计费大类,包括:物流头程段0、海外仓储段1、尾程配送段2',
`money_type` varchar(255) NOT NULL COMMENT '费用类型,头程包括:海运费、空运费;仓储包括:0收货上架费、1库内操作费 、2库内仓储费、3退货处理费、4 返厂处理费;尾程包括:配送费、揽收费',
`factor1` varchar(255) NOT NULL COMMENT '计费因子1:头程|:目的国;仓库:商品分类;尾程:城市',
`factor2` varchar(255) NOT NULL COMMENT '计费因子2,头程:物流渠道(赛拾、天龙);仓库:首件/单、续件/单;尾程:首重/续重',
`factor3` varchar(255) DEFAULT NULL COMMENT '计费因子3:备用',
`factor4` varchar(255) DEFAULT NULL COMMENT '计费因子4:备用',
`factor5` varchar(255) DEFAULT NULL COMMENT '计费因子5:备用',
`factor6` varchar(255) DEFAULT NULL COMMENT '计费因子6:备用',
`factor7` varchar(255) DEFAULT NULL COMMENT '计费因子7:备用',
`factor8` varchar(255) DEFAULT NULL COMMENT '计费因子8:备用',
`factor9` varchar(255) DEFAULT NULL COMMENT '计费因子9:备用',
`factor10` varchar(255) DEFAULT NULL COMMENT '计费因子10:备用',
`rate` float(12,4) NOT NULL COMMENT '费率',
`order_sn` varchar(20) NOT NULL DEFAULT '' COMMENT '平台订单号',
`store_id` int(11) NOT NULL DEFAULT '0' COMMENT '商家id',
`type_id` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1 肯尼亚 2尼日利亚 3乌干达',
`receivable_money` float(10,5) NOT NULL DEFAULT '0.00000' COMMENT '应收金额',
`real_money` float(10,5) NOT NULL DEFAULT '0.00000' COMMENT '实收金额',
`payable_money` float(10,5) NOT NULL DEFAULT '0.00000',
`paid_money` float(10,5) NOT NULL DEFAULT '0.00000' COMMENT '实际支付金额',
`pay_direct` tinyint(1) NOT NULL DEFAULT '0' COMMENT '交易方向:0 应收 1 应付',
`pay_type` varchar(5) NOT NULL DEFAULT '' COMMENT '交易类型 预付充值、扣款、转账',
`biz_status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '交易状态',
`settlement_status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '结算状态',
`is_paid` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否支付 0 未支付 1支付',
`account` varchar(255) NOT NULL DEFAULT '' COMMENT '支付账户',
`transit_id` varchar(20) NOT NULL DEFAULT '' COMMENT '交易流水号',
`add_time` int(11) NOT NULL DEFAULT '0',
`pay_time` int(11) NOT NULL DEFAULT '0' COMMENT '流水时间',
`servicer_id` int(11) NOT NULL DEFAULT '0',
`waybill_number` varchar(20) NOT NULL DEFAULT '',
`city` varchar(255) NOT NULL COMMENT '城市',
`weight` double(10,2) NOT NULL COMMENT '重量',
`date` date NOT NULL,
`class_id` int(3) NOT NULL,
`store_name` varchar(255) NOT NULL DEFAULT '' COMMENT '店铺名',
`quantity` int(11) NOT NULL COMMENT '数量',
`sku_id` varchar(20) NOT NULL COMMENT 'sku,为DMS、WMS上传的系统',
`goods_name` varchar(255) NOT NULL DEFAULT '' COMMENT 'goods_name',
`pay_user_id` int(11) NOT NULL DEFAULT '0' COMMENT '当时扣款所属的用户ID,非创建时d的ID。(主要用于创建店铺更改用户时的情况)',
`user_id` int(11) NOT NULL DEFAULT '0' COMMENT '用户ID',
`index` varchar(20) NOT NULL DEFAULT '0' COMMENT '用于区分是否多次传输次数',
`seller_id` int(11) NOT NULL DEFAULT '0' COMMENT 'kili_sellers 表的主键,不是wms、dms推送过来的seller_id,seller_id 可以根据store_id,type_id 推算出'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_freight_bak
-- ----------------------------
DROP TABLE IF EXISTS `kili_freight_bak`;
CREATE TABLE `kili_freight_bak` (
`id` int(11) NOT NULL DEFAULT '0' COMMENT '支付方向',
`charge_type` varchar(255) NOT NULL COMMENT '计费大类,包括:物流头程段0、海外仓储段1、尾程配送段2',
`money_type` varchar(255) NOT NULL COMMENT '费用类型,头程包括:海运费、空运费;仓储包括:0收货上架费、1库内操作费 、2库内仓储费、3退货处理费、4 返厂处理费;尾程包括:配送费、揽收费',
`factor1` varchar(255) NOT NULL COMMENT '计费因子1:头程|:目的国;仓库:商品分类;尾程:城市',
`factor2` varchar(255) NOT NULL COMMENT '计费因子2,头程:物流渠道(赛拾、天龙);仓库:首件/单、续件/单;尾程:首重/续重',
`factor3` varchar(255) DEFAULT NULL COMMENT '计费因子3:备用',
`factor4` varchar(255) DEFAULT NULL COMMENT '计费因子4:备用',
`factor5` varchar(255) DEFAULT NULL COMMENT '计费因子5:备用',
`factor6` varchar(255) DEFAULT NULL COMMENT '计费因子6:备用',
`factor7` varchar(255) DEFAULT NULL COMMENT '计费因子7:备用',
`factor8` varchar(255) DEFAULT NULL COMMENT '计费因子8:备用',
`factor9` varchar(255) DEFAULT NULL COMMENT '计费因子9:备用',
`factor10` varchar(255) DEFAULT NULL COMMENT '计费因子10:备用',
`rate` float(12,4) NOT NULL COMMENT '费率',
`order_sn` varchar(20) NOT NULL DEFAULT '' COMMENT '平台订单号',
`seller_id` varchar(255) NOT NULL DEFAULT '0' COMMENT '商家id',
`type_id` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1 肯尼亚 2尼日利亚 3乌干达',
`receivable_money` float(10,2) DEFAULT '0.00' COMMENT '应收金额',
`real_money` float(10,2) NOT NULL DEFAULT '0.00' COMMENT '实收金额',
`payable_money` float(10,2) NOT NULL DEFAULT '0.00',
`paid_money` float(10,2) NOT NULL DEFAULT '0.00' COMMENT '实际支付金额',
`pay_direct` tinyint(1) NOT NULL DEFAULT '0' COMMENT '交易方向:0 应收 1 应付',
`pay_type` varchar(5) NOT NULL DEFAULT '' COMMENT '交易类型 预付充值、扣款、转账',
`biz_status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '交易状态',
`settlement_status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '结算状态',
`is_paid` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否支付 0 未支付 1支付',
`account` varchar(255) NOT NULL DEFAULT '' COMMENT '支付账户',
`transit_id` varchar(20) NOT NULL DEFAULT '' COMMENT '交易流水号',
`add_time` int(11) NOT NULL DEFAULT '0',
`pay_time` int(11) NOT NULL DEFAULT '0' COMMENT '流水时间',
`servicer_id` int(11) NOT NULL DEFAULT '0',
`waybill_number` varchar(20) NOT NULL DEFAULT '',
`city` varchar(255) NOT NULL COMMENT '城市',
`weight` double(10,2) NOT NULL COMMENT '重量',
`date` date NOT NULL,
`class_id` int(3) NOT NULL,
`seller_name` varchar(255) NOT NULL COMMENT '卖家名',
`quantity` int(11) NOT NULL COMMENT '数量',
`sku` varchar(20) NOT NULL COMMENT 'sku',
`pay_user_id` int(11) NOT NULL DEFAULT '0' COMMENT '当时扣款所属的用户ID,非创建时d的ID。(主要用于创建店铺更改用户时的情况)',
`user_id` int(11) NOT NULL DEFAULT '0' COMMENT '用户ID'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_goods
-- ----------------------------
DROP TABLE IF EXISTS `kili_goods`;
CREATE TABLE `kili_goods` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`sku` int(11) NOT NULL COMMENT '商品id',
`store_id` int(11) NOT NULL COMMENT '店铺id',
`type_id` tinyint(4) NOT NULL COMMENT '所属仓库',
`goods_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '商品名称',
`price` decimal(10,2) NOT NULL COMMENT '商品价格',
PRIMARY KEY (`id`),
UNIQUE KEY `sku` (`sku`,`type_id`) USING BTREE COMMENT '唯一索引'
) ENGINE=InnoDB AUTO_INCREMENT=21020 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for kili_goods_class
-- ----------------------------
DROP TABLE IF EXISTS `kili_goods_class`;
CREATE TABLE `kili_goods_class` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`class_name_en` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`class_name_cn` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`price` double(8,2) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1705 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for kili_goods_class1
-- ----------------------------
DROP TABLE IF EXISTS `kili_goods_class1`;
CREATE TABLE `kili_goods_class1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`class_id` int(2) NOT NULL,
`class_name_en` varchar(255) NOT NULL,
`class_name_cn` varchar(255) NOT NULL,
`price` decimal(10,4) NOT NULL DEFAULT '0.0000',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_logistics_type
-- ----------------------------
DROP TABLE IF EXISTS `kili_logistics_type`;
CREATE TABLE `kili_logistics_type` (
`id` int(5) NOT NULL AUTO_INCREMENT COMMENT '主键',
`type` varchar(50) NOT NULL COMMENT '接口类型',
`name` varchar(255) DEFAULT NULL COMMENT '接口名',
`remark` varchar(255) DEFAULT NULL COMMENT '此类型需要注意事项',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='运单类型表(物流轨迹,运单类型),此表将会给平台用户展示。需要的接口字段,均会展示于此 ';
-- ----------------------------
-- Table structure for kili_overdue
-- ----------------------------
DROP TABLE IF EXISTS `kili_overdue`;
CREATE TABLE `kili_overdue` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`amount` double(8,2) NOT NULL COMMENT '欠款金额',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for kili_payment
-- ----------------------------
DROP TABLE IF EXISTS `kili_payment`;
CREATE TABLE `kili_payment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT '1' COMMENT '1 获取支付效验码接口',
`url` varchar(255) NOT NULL,
`merchant_id` varchar(255) DEFAULT NULL COMMENT '商户号',
`key` varchar(255) DEFAULT '' COMMENT '签名',
`remark` varchar(255) DEFAULT NULL COMMENT '说明',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`seller_id` varchar(12) DEFAULT NULL,
`seller_account` varchar(255) DEFAULT NULL,
`buyer_id` varchar(12) DEFAULT NULL,
`buyer_account` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_payment_order
-- ----------------------------
DROP TABLE IF EXISTS `kili_payment_order`;
CREATE TABLE `kili_payment_order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`waybill_id` int(11) DEFAULT '0' COMMENT '运单ID',
`waybill_number` varchar(20) DEFAULT '' COMMENT '运单号',
`amount` decimal(10,2) DEFAULT '0.00' COMMENT '已收到金额',
`pay_time` int(11) DEFAULT '0' COMMENT '支付时间',
`pay_from` int(11) DEFAULT '0' COMMENT '支付渠道',
`lipapay_order_id` varchar(60) DEFAULT NULL COMMENT 'lipapay流水',
`trans_id` varchar(60) DEFAULT NULL COMMENT '银行流水',
`pay_sn` varchar(20) DEFAULT NULL COMMENT '支付号',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='地区表,用于快递公司地区配置,考虑到一对一或多对多,暂时用分开';
-- ----------------------------
-- Table structure for kili_platform
-- ----------------------------
DROP TABLE IF EXISTS `kili_platform`;
CREATE TABLE `kili_platform` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`code` varchar(20) NOT NULL DEFAULT '' COMMENT ' 平台代码',
`name` varchar(255) NOT NULL COMMENT '平台名称',
`key` varchar(255) NOT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_receiver_info
-- ----------------------------
DROP TABLE IF EXISTS `kili_receiver_info`;
CREATE TABLE `kili_receiver_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`waybill_id` int(11) NOT NULL,
`receiver_contactname` varchar(255) DEFAULT NULL,
`receiver_contactnumber` varchar(255) DEFAULT NULL,
`receiver_country` varchar(255) DEFAULT NULL,
`receiver_province` varchar(255) DEFAULT NULL,
`receiver_city` varchar(255) DEFAULT NULL,
`receiver_address1` varchar(255) NOT NULL,
`receiver_address2` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=316 DEFAULT CHARSET=utf8 COMMENT='收件人相关地址表';
-- ----------------------------
-- Table structure for kili_sellers
-- ----------------------------
DROP TABLE IF EXISTS `kili_sellers`;
CREATE TABLE `kili_sellers` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`store_id` int(11) NOT NULL,
`type_id` tinyint(4) NOT NULL,
`store_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`user_id` int(11) NOT NULL COMMENT '用户表id',
`seller_id` int(11) NOT NULL COMMENT 'BBC 的seller_id,在系统中未使用,仅仅标记',
PRIMARY KEY (`id`),
UNIQUE KEY `store_id` (`store_id`,`type_id`) USING BTREE COMMENT 'store_id,type_id 唯一'
) ENGINE=InnoDB AUTO_INCREMENT=3313 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for kili_sender_info
-- ----------------------------
DROP TABLE IF EXISTS `kili_sender_info`;
CREATE TABLE `kili_sender_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`waybill_id` int(11) NOT NULL,
`sender_contactname` varchar(255) DEFAULT NULL,
`sender_contactnumber` varchar(255) DEFAULT NULL,
`sender_country` varchar(255) DEFAULT NULL,
`sender_province` varchar(255) DEFAULT NULL,
`sender_city` varchar(255) DEFAULT NULL,
`sender_address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=261 DEFAULT CHARSET=utf8 COMMENT='发件人相关地址表';
-- ----------------------------
-- Table structure for kili_settings
-- ----------------------------
DROP TABLE IF EXISTS `kili_settings`;
CREATE TABLE `kili_settings` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`key` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
`value` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`group` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for kili_settlement
-- ----------------------------
DROP TABLE IF EXISTS `kili_settlement`;
CREATE TABLE `kili_settlement` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`amount` decimal(10,2) DEFAULT '0.00' COMMENT '批次结算金额',
`status` int(11) NOT NULL DEFAULT '0' COMMENT '结算状态 0未处理 10 申请中 20 拒绝 30 完成',
`add_time` int(11) DEFAULT '0' COMMENT '时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='地区表,用于快递公司地区配置,考虑到一对一或多对多,暂时用分开';
-- ----------------------------
-- Table structure for kili_settlement_orders
-- ----------------------------
DROP TABLE IF EXISTS `kili_settlement_orders`;
CREATE TABLE `kili_settlement_orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`waybill_id` int(11) DEFAULT '0' COMMENT '运单ID',
`settlement_id` int(11) DEFAULT '0' COMMENT '结算ID',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='地区表,用于快递公司地区配置,考虑到一对一或多对多,暂时用分开';
-- ----------------------------
-- Table structure for kili_shipping_method
-- ----------------------------
DROP TABLE IF EXISTS `kili_shipping_method`;
CREATE TABLE `kili_shipping_method` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`shipping_code` varchar(30) NOT NULL COMMENT '配送方式名称(英文)',
`shipping_cnname` varchar(30) NOT NULL COMMENT '配送方式中文名',
`shipping_enname` varchar(30) NOT NULL COMMENT '英文名',
`courier_id` int(6) NOT NULL COMMENT '所属快递公司id',
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`) USING BTREE,
KEY `id_2` (`id`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_tms
-- ----------------------------
DROP TABLE IF EXISTS `kili_tms`;
CREATE TABLE `kili_tms` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`app_key` varchar(255) DEFAULT '' COMMENT '深圳中转仓',
`country` varchar(20) DEFAULT NULL,
`app_secret` varchar(255) DEFAULT NULL,
`url` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_transaction
-- ----------------------------
DROP TABLE IF EXISTS `kili_transaction`;
CREATE TABLE `kili_transaction` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT '用户名',
`money` decimal(8,2) NOT NULL COMMENT '充值记录',
`bank` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '银行名称',
`money_type` tinyint(1) NOT NULL DEFAULT '1' COMMENT '金额币种',
`real_name` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '打款人',
`bank_account` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '银行账户',
`trans_id` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '流水号',
`img` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '商家上传的图片',
`admin_user_id` int(11) NOT NULL DEFAULT '0' COMMENT '审核人',
`remark` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '审批记录',
`status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '状态,0 待审核 1同意 2不同意',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`review_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `NewIndex1` (`bank_account`,`trans_id`)
) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for kili_waybill
-- ----------------------------
DROP TABLE IF EXISTS `kili_waybill`;
CREATE TABLE `kili_waybill` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`waybill_number` varchar(20) DEFAULT NULL COMMENT '系统生成的物流订单号',
`outorder_oid` varchar(25) DEFAULT '' COMMENT '出库号',
`pay_sn` varchar(20) DEFAULT '' COMMENT '支付码',
`order_platform` enum('KILIMALL_KE','KILIMALL_NG','KILIMALL_UG','Other') NOT NULL COMMENT '订单生成平台',
`tracking_number` varchar(20) DEFAULT NULL COMMENT '跟踪号,由快递公司生成',
`order_type` varchar(20) NOT NULL DEFAULT '' COMMENT '订单类型:1:gs 2:ds',
`status` int(6) DEFAULT '10' COMMENT '0(已取消) 10(待处理) 20(商家已确认发货--适用于GS类型订单) 30(已入中国分拣中心--适用于GS类型订单) 40(已出中国分拣中心--适用于GS类型订单) 50(已入非洲分拣中心--适用于GS类型订单) 60(等待派件) 70(派件中) 80(客户已签收) 90(客户拒收) 100(已退商家海外退件仓---适用于GS类型订单) 110(已退回商家) 120(退给商家失败) 210(已从商家那揽收成功) 220(从商家那揽收失败)',
`client_id` int(11) DEFAULT '0' COMMENT '商家表主键id',
`courier_id` int(11) DEFAULT '0' COMMENT '快递公司表id',
`add_time` int(11) NOT NULL DEFAULT '0' COMMENT '订单创建时间',
`country_id` tinyint(4) DEFAULT '0' COMMENT '国家信息表主键id',
`order_amount` decimal(10,2) DEFAULT '0.00' COMMENT '订单金额',
`pod_amount` decimal(10,2) DEFAULT '0.00' COMMENT '代收金额',
`is_pickup` tinyint(1) NOT NULL DEFAULT '1',
`is_pod` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否货到付款 0否 1是',
`counter_fee` decimal(10,2) DEFAULT '0.00' COMMENT '代收手续费',
`delivery_type` int(11) DEFAULT '0' COMMENT '买家配送类型(0配送上门,1自提)',
`payed_money` decimal(10,2) NOT NULL DEFAULT '0.00',
`payment_time` int(11) DEFAULT '0' COMMENT '收款时间',
`settlement_status` int(11) DEFAULT '0' COMMENT '结算状态 0未处理 10 申请中 20 拒绝 30 完成',
`settlement_time` int(11) DEFAULT '0' COMMENT '结算时间',
`client_ordersn` varchar(50) DEFAULT '',
`warehouse_id` int(11) DEFAULT '0' COMMENT '海外仓',
`client_code` varchar(20) DEFAULT '',
`pickup_startdate` int(11) NOT NULL DEFAULT '0',
`pickup_enddata` int(11) NOT NULL DEFAULT '0',
`order_weight` decimal(10,2) NOT NULL DEFAULT '0.00',
`currency` varchar(20) NOT NULL DEFAULT '' COMMENT '币种',
`mail_cargo_type` varchar(20) NOT NULL DEFAULT '',
`order_note` varchar(20) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `waybill_number_index` (`waybill_number`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_waybill_details
-- ----------------------------
DROP TABLE IF EXISTS `kili_waybill_details`;
CREATE TABLE `kili_waybill_details` (
`waybill_id` int(10) NOT NULL DEFAULT '0',
`pickup_type` int(4) DEFAULT NULL COMMENT '是否通知上门取货 0 否 1是',
`pickup_startdate` datetime DEFAULT NULL COMMENT '上门取货开始时间',
`pickup_endate` datetime DEFAULT NULL COMMENT '上门取货结束时间',
`sender_name` varchar(30) DEFAULT NULL COMMENT '发货人姓名',
`sender_contactnumber` varchar(15) DEFAULT NULL COMMENT '发货人手机号码',
`sender_country` varchar(30) DEFAULT '' COMMENT '发货人国家',
`sender_province` varchar(30) DEFAULT '',
`sender_city` varchar(30) DEFAULT '',
`sender_address` varchar(30) DEFAULT '',
`receiver_country` varchar(30) DEFAULT '',
`receiver_name` varchar(30) DEFAULT '',
`receiver_province` varchar(30) DEFAULT NULL,
`receiver_city` varchar(30) DEFAULT NULL,
`receiver_address` varchar(30) DEFAULT NULL,
`weight` decimal(10,2) DEFAULT NULL,
`is_pod` int(4) unsigned zerofill DEFAULT NULL COMMENT '是否货到付款 0否 1是',
`order_amount` decimal(10,2) DEFAULT NULL COMMENT '订单总金额',
`pod_amount` decimal(10,2) DEFAULT NULL COMMENT '代收金额',
`counter_fee` decimal(10,0) DEFAULT NULL COMMENT '手续费',
`delivery_type` int(4) DEFAULT NULL COMMENT '配送类型(0配送上门,1自提)',
PRIMARY KEY (`waybill_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_waybill_goods
-- ----------------------------
DROP TABLE IF EXISTS `kili_waybill_goods`;
CREATE TABLE `kili_waybill_goods` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`waybill_id` varchar(20) DEFAULT NULL COMMENT '生成自己的唯一运单号',
`item_title` varchar(255) DEFAULT '' COMMENT '商品标题',
`sale_price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '销售价格',
`pay_price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '支付价格',
`invoice_enname` varchar(255) DEFAULT NULL COMMENT '申报英文名',
`invoice_cnname` varchar(255) DEFAULT NULL COMMENT '申报中文名',
`invoice_price` decimal(10,2) DEFAULT '0.00' COMMENT '申报价格',
`weight` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '重量',
`length` decimal(10,2) NOT NULL DEFAULT '0.00',
`height` decimal(10,2) NOT NULL DEFAULT '0.00',
`width` decimal(10,2) NOT NULL DEFAULT '0.00',
`unit_code` enum('MTR','PCE','SET') DEFAULT 'PCE' COMMENT '单位',
`contain_battery` int(11) NOT NULL DEFAULT '0' COMMENT '是否含电。0不含,1含',
`quantity` int(7) NOT NULL DEFAULT '0' COMMENT '商品数量',
`item_skucode` varchar(255) NOT NULL DEFAULT '' COMMENT '商品skuid',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=112 DEFAULT CHARSET=utf8 COMMENT='运单商品表';
-- ----------------------------
-- Table structure for kili_waybill_log
-- ----------------------------
DROP TABLE IF EXISTS `kili_waybill_log`;
CREATE TABLE `kili_waybill_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`waybill_id` int(11) NOT NULL DEFAULT '0' COMMENT '系统生成的物流订单号',
`platform` varchar(8) NOT NULL DEFAULT '' COMMENT '平台 tms wms courier client pay',
`operating_time` int(11) NOT NULL DEFAULT '0' COMMENT '操作时间',
`status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '状态',
`user_id` int(11) NOT NULL DEFAULT '0',
`platform_user` varchar(30) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_waybill_payment_orders
-- ----------------------------
DROP TABLE IF EXISTS `kili_waybill_payment_orders`;
CREATE TABLE `kili_waybill_payment_orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`waybill_id` int(11) NOT NULL DEFAULT '0' COMMENT '运单ID',
`waybill_number` varchar(20) NOT NULL DEFAULT '' COMMENT '运单号',
`amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '已收到金额',
`pay_time` int(11) NOT NULL DEFAULT '0' COMMENT '支付时间',
`pay_from` varchar(20) NOT NULL DEFAULT '' COMMENT '支付渠道',
`lipapay_order_id` varchar(60) NOT NULL DEFAULT '' COMMENT 'lipapay流水',
`trans_id` varchar(60) NOT NULL DEFAULT '' COMMENT '银行流水',
`pay_sn` varchar(20) NOT NULL DEFAULT '' COMMENT '支付号',
`type` tinyint(1) NOT NULL DEFAULT '0' COMMENT '支付类型(1 默认online 2 默认rider)',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=63 DEFAULT CHARSET=utf8 COMMENT='地区表,用于快递公司地区配置,考虑到一对一或多对多,暂时用分开';
-- ----------------------------
-- Table structure for kili_waybill_track
-- ----------------------------
DROP TABLE IF EXISTS `kili_waybill_track`;
CREATE TABLE `kili_waybill_track` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`waybill_number` int(11) NOT NULL DEFAULT '0' COMMENT '运单号',
`tracking_number` varchar(20) NOT NULL DEFAULT '' COMMENT '跟踪号',
`waybill_id` int(11) NOT NULL DEFAULT '0' COMMENT '运单表主键id',
`track_code` int(6) NOT NULL DEFAULT '0',
`add_time` int(11) NOT NULL DEFAULT '0' COMMENT '发生时间',
`location` varchar(20) NOT NULL DEFAULT '',
`express_id` int(6) NOT NULL DEFAULT '0' COMMENT '快递公司id',
`express_name` varchar(255) NOT NULL DEFAULT '',
`client_ordersn` varchar(30) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_waybill_trackcode
-- ----------------------------
DROP TABLE IF EXISTS `kili_waybill_trackcode`;
CREATE TABLE `kili_waybill_trackcode` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`status_desc` text COMMENT '内容',
`status_code` varchar(20) DEFAULT '' COMMENT '事件代码',
`memo` text NOT NULL COMMENT '备注说明',
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_waybill_track_code
-- ----------------------------
DROP TABLE IF EXISTS `kili_waybill_track_code`;
CREATE TABLE `kili_waybill_track_code` (
`id` int(10) NOT NULL DEFAULT '0',
`status_desc` text COMMENT '内容',
`status_code` varchar(20) DEFAULT NULL COMMENT '事件代码',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_waybill_track_record
-- ----------------------------
DROP TABLE IF EXISTS `kili_waybill_track_record`;
CREATE TABLE `kili_waybill_track_record` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`waybill_number` varchar(30) DEFAULT NULL COMMENT '运单号',
`status` int(6) DEFAULT NULL COMMENT '表的状态',
`remark` varchar(100) DEFAULT NULL COMMENT '物流详细信息',
`position` varchar(100) DEFAULT NULL COMMENT '发生位置',
`express_id` int(6) DEFAULT NULL COMMENT '快递公司id',
`add_time` datetime DEFAULT NULL COMMENT '发生时间',
`contact_name` varchar(30) DEFAULT NULL,
`contact_phone` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_waybill_type
-- ----------------------------
DROP TABLE IF EXISTS `kili_waybill_type`;
CREATE TABLE `kili_waybill_type` (
`id` int(5) NOT NULL AUTO_INCREMENT COMMENT '主键',
`code` varchar(5) NOT NULL DEFAULT '' COMMENT '代码',
`name` varchar(255) DEFAULT '' COMMENT '接口名',
`remark` varchar(255) DEFAULT '' COMMENT '此类型需要注意事项',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COMMENT='运单类型表(物流轨迹,运单类型),此表将会给平台用户展示。需要的接口字段,均会展示于此 ';
-- ----------------------------
-- Table structure for kili_waybill_unnormal
-- ----------------------------
DROP TABLE IF EXISTS `kili_waybill_unnormal`;
CREATE TABLE `kili_waybill_unnormal` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`client_ordersn` varchar(20) DEFAULT '' COMMENT '客户订单号',
`waybill_number` int(20) DEFAULT '0' COMMENT '运单号',
`type` int(4) DEFAULT '0' COMMENT '异常件类型',
`add_time` datetime DEFAULT NULL COMMENT '标记时间',
`remark` varchar(100) DEFAULT '' COMMENT '备注',
`operator` varchar(255) DEFAULT '' COMMENT '操作人名称',
`org` varchar(50) DEFAULT '' COMMENT '操作人所在部门',
`rider` varchar(50) DEFAULT '' COMMENT '快递员名称',
`courier` varchar(50) DEFAULT '' COMMENT '快递员公司名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_weicheng_freight
-- ----------------------------
DROP TABLE IF EXISTS `kili_weicheng_freight`;
CREATE TABLE `kili_weicheng_freight` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '支付方向',
`charge_type` varchar(255) NOT NULL COMMENT '计费大类,包括:物流头程段1、海外仓储段2、尾程配送段3',
`money_type` varchar(255) NOT NULL COMMENT '费用类型,头程包括:海运费、空运费;仓储包括:收货上架费、库内操作费、库内仓储费、退货处理费、返厂处理费;尾程包括:0 配送费、1 揽收费',
`factor1` varchar(255) NOT NULL COMMENT '计费因子1:头程|:目的国;仓库:商品分类;尾程:城市',
`factor2` varchar(255) NOT NULL COMMENT '计费因子2,头程:物流渠道(赛拾、天龙);仓库:首件/单、续件/单;尾程:首重/续重',
`factor3` varchar(255) DEFAULT NULL COMMENT '计费因子3:备用',
`factor4` varchar(255) DEFAULT NULL COMMENT '计费因子4:备用',
`factor5` varchar(255) DEFAULT NULL COMMENT '计费因子5:备用',
`factor6` varchar(255) DEFAULT NULL COMMENT '计费因子6:备用',
`factor7` varchar(255) DEFAULT NULL COMMENT '计费因子7:备用',
`factor8` varchar(255) DEFAULT NULL COMMENT '计费因子8:备用',
`factor9` varchar(255) DEFAULT NULL COMMENT '计费因子9:备用',
`factor10` varchar(255) DEFAULT NULL COMMENT '计费因子10:备用',
`rate` float(12,4) NOT NULL COMMENT '费率',
`order_sn` varchar(20) NOT NULL DEFAULT '' COMMENT '平台订单号',
`seller_id` varchar(255) NOT NULL DEFAULT '0' COMMENT '商家id',
`seller_name` varchar(255) NOT NULL DEFAULT '',
`receivable_money` float(10,2) DEFAULT '0.00' COMMENT '应收金额',
`real_money` float(10,2) NOT NULL DEFAULT '0.00' COMMENT '实收金额',
`payable_money` float(10,2) NOT NULL DEFAULT '0.00',
`paid_money` float(10,2) NOT NULL DEFAULT '0.00' COMMENT '实际支付金额',
`pay_direct` tinyint(1) NOT NULL DEFAULT '0' COMMENT '交易方向 0 应收 1应付',
`pay_type` varchar(5) NOT NULL DEFAULT '' COMMENT '交易类型 预付充值、扣款、转账',
`biz_status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '交易状态',
`settlement_status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '结算状态',
`is_paid` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否支付',
`account` varchar(255) NOT NULL DEFAULT '' COMMENT '支付账户',
`transit_id` varchar(20) NOT NULL DEFAULT '' COMMENT '交易流水号',
`add_time` int(11) NOT NULL DEFAULT '0',
`pay_time` int(11) NOT NULL DEFAULT '0' COMMENT '流水时间',
`customer_id` varchar(255) NOT NULL DEFAULT '',
`servicer_id` int(11) NOT NULL DEFAULT '0',
`waybill_number` varchar(20) NOT NULL DEFAULT '',
`city` varchar(255) NOT NULL COMMENT '城市',
`weight` double(10,2) NOT NULL COMMENT '重量',
`date` date DEFAULT NULL,
`class_id` int(2) NOT NULL COMMENT 'class_id 分类id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1566 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_wms_outbound
-- ----------------------------
DROP TABLE IF EXISTS `kili_wms_outbound`;
CREATE TABLE `kili_wms_outbound` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`outbound_oid` varchar(20) DEFAULT NULL COMMENT '系统生成的出库单号',
`wms_number` varchar(30) NOT NULL COMMENT 'wms生成的出库单号',
`waybill_id` varchar(20) DEFAULT NULL COMMENT '运单表主键id',
`warehouse_code` varchar(30) NOT NULL COMMENT '仓库编码。唯一。可查询',
`client_ordersn` varchar(30) NOT NULL COMMENT '客户订单参考号',
`order_platform` enum('KILIMALL_KE','KILIMALL_NG','KILIMALL_UG','Other') NOT NULL COMMENT '订单生成平台',
`status` int(6) DEFAULT '0' COMMENT '出库单状态',
`client_id` int(11) DEFAULT '0' COMMENT '商家表主键id',
`courier_id` int(11) DEFAULT '0' COMMENT '快递公司号码',
`add_time` int(11) NOT NULL DEFAULT '0' COMMENT '时间戳',
`order_amount` decimal(10,2) DEFAULT '0.00' COMMENT '订单金额',
`pod_amount` decimal(10,2) DEFAULT '0.00' COMMENT '代收金额',
`is_pod` int(11) DEFAULT '0' COMMENT '是否货到付款 0否 1是',
`delivery_type` int(11) DEFAULT '0' COMMENT '配送类型(0配送上门,1自提)',
`pay_sn` varchar(20) DEFAULT '' COMMENT '支付码',
PRIMARY KEY (`id`),
UNIQUE KEY `waybill_number_index` (`outbound_oid`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_wms_outbound_goods
-- ----------------------------
DROP TABLE IF EXISTS `kili_wms_outbound_goods`;
CREATE TABLE `kili_wms_outbound_goods` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`outbound_id` int(11) DEFAULT '0' COMMENT '出库单表主键id',
`item_skucode` varchar(20) DEFAULT '' COMMENT '产品编码。外部编码(用于商城平台上和仓库系统之间的映射)',
`quantity` int(5) NOT NULL DEFAULT '0' COMMENT '商品数量',
`sale_price` decimal(10,2) DEFAULT '0.00' COMMENT '商品销售价格',
`pay_price` decimal(10,2) NOT NULL COMMENT '商品支付价格',
`curtype` tinyint(1) DEFAULT '1' COMMENT '货币类型 1:人民币 2先令',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='出库单商品明细表';
-- ----------------------------
-- Table structure for kili_wms_warehouse
-- ----------------------------
DROP TABLE IF EXISTS `kili_wms_warehouse`;
CREATE TABLE `kili_wms_warehouse` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`wh_code` varchar(30) NOT NULL DEFAULT '' COMMENT '仓库编码',
`wh_name` varchar(30) NOT NULL DEFAULT '' COMMENT '仓库名称',
`contactnumber` varchar(20) NOT NULL DEFAULT '' COMMENT '联系方式',
`address` varchar(200) NOT NULL DEFAULT '' COMMENT '仓库详细地址',
`country_id` int(11) NOT NULL,
`app_key` varchar(255) NOT NULL DEFAULT '',
`app_secret` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for kili_wms_warehouse_apiurl
-- ----------------------------
DROP TABLE IF EXISTS `kili_wms_warehouse_apiurl`;
CREATE TABLE `kili_wms_warehouse_apiurl` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`wms_id` int(11) NOT NULL DEFAULT '0' COMMENT '用户id',
`url` varchar(255) NOT NULL DEFAULT '',
`remark` varchar(255) DEFAULT '' COMMENT '说明',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`type` varchar(25) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for migrations
-- ----------------------------
DROP TABLE IF EXISTS `migrations`;
CREATE TABLE `migrations` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for nc_goods_class
-- ----------------------------
DROP TABLE IF EXISTS `nc_goods_class`;
CREATE TABLE `nc_goods_class` (
`gc_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '索引ID',
`gc_name` varchar(100) NOT NULL COMMENT '分类名称',
`type_id` int(10) unsigned NOT NULL COMMENT '类型id',
`type_name` varchar(100) NOT NULL COMMENT '类型名称',
`gc_parent_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '父ID',
`gc_description` varchar(255) NOT NULL DEFAULT '' COMMENT '描述',
`updated_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
PRIMARY KEY (`gc_id`),
KEY `store_id` (`gc_parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='商品分类表';
-- ----------------------------
-- Table structure for password_resets
-- ----------------------------
DROP TABLE IF EXISTS `password_resets`;
CREATE TABLE `password_resets` (
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
KEY `password_resets_email_index` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for seller
-- ----------------------------
DROP TABLE IF EXISTS `seller`;
CREATE TABLE `seller` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`seller_id` int(11) NOT NULL,
`seller_name` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2135 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for store
-- ----------------------------
DROP TABLE IF EXISTS `store`;
CREATE TABLE `store` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`store_id` int(11) NOT NULL,
`seller_id` int(11) NOT NULL,
`type_id` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9336 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for tasks
-- ----------------------------
DROP TABLE IF EXISTS `tasks`;
CREATE TABLE `tasks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`command_name` varchar(255) NOT NULL,
`add_time` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for test
-- ----------------------------
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`time` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3370 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`remember_token` varchar(100) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`type_id` tinyint(4) NOT NULL DEFAULT '1' COMMENT '平台id 1 肯尼亚 2尼日利亚 3 乌干达',
`seller_id` int(11) NOT NULL DEFAULT '0',
`avatar` varchar(255) NOT NULL DEFAULT '' COMMENT '用户头像',
`balance` float(10,2) NOT NULL DEFAULT '0.00' COMMENT '余额',
`overdue` float(10,3) NOT NULL DEFAULT '0.000' COMMENT '确实的金额,用负数表示。。。',
`is_reset_password` tinyint(1) NOT NULL DEFAULT '0' COMMENT '0 没有更改密码 1更改密码',
PRIMARY KEY (`id`),
UNIQUE KEY `index_name` (`name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2282 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for zcharge_deliver
-- ----------------------------
DROP TABLE IF EXISTS `zcharge_deliver`;
CREATE TABLE `zcharge_deliver` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '支付方向',
`charge_type` varchar(255) NOT NULL COMMENT '计费大类,包括:物流头程段1、海外仓储段2、尾程配送段3',
`money_type` varchar(255) NOT NULL COMMENT '费用类型,头程包括:海运费、空运费;仓储包括:收货上架费、库内操作费、库内仓储费、退货处理费、返厂处理费;尾程包括:0 配送费、1 揽收费',
`factor1` varchar(255) NOT NULL COMMENT '计费因子1:头程|:目的国;仓库:商品分类;尾程:城市',
`factor2` varchar(255) NOT NULL COMMENT '计费因子2,头程:物流渠道(赛拾、天龙);仓库:首件/单、续件/单;尾程:首重/续重',
`factor3` varchar(255) DEFAULT NULL COMMENT '计费因子3:备用',
`factor4` varchar(255) DEFAULT NULL COMMENT '计费因子4:备用',
`factor5` varchar(255) DEFAULT NULL COMMENT '计费因子5:备用',
`factor6` varchar(255) DEFAULT NULL COMMENT '计费因子6:备用',
`factor7` varchar(255) DEFAULT NULL COMMENT '计费因子7:备用',
`factor8` varchar(255) DEFAULT NULL COMMENT '计费因子8:备用',
`factor9` varchar(255) DEFAULT NULL COMMENT '计费因子9:备用',
`factor10` varchar(255) DEFAULT NULL COMMENT '计费因子10:备用',
`rate` float(12,4) NOT NULL COMMENT '费率',
`order_sn` varchar(20) NOT NULL DEFAULT '' COMMENT '平台订单号',
`seller_id` varchar(255) NOT NULL DEFAULT '0' COMMENT '商家id',
`receivable_money` float(10,2) NOT NULL DEFAULT '0.00' COMMENT '应收金额',
`real_money` float(10,2) NOT NULL DEFAULT '0.00' COMMENT '实收金额',
`payable_money` float(10,2) NOT NULL DEFAULT '0.00',
`paid_money` float(10,2) NOT NULL DEFAULT '0.00' COMMENT '实际支付金额',
`pay_direct` tinyint(1) NOT NULL DEFAULT '0' COMMENT '交易方向 0 应收 1应付',
`pay_type` varchar(5) NOT NULL DEFAULT '' COMMENT '交易类型 预付充值、扣款、转账',
`biz_status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '交易状态',
`settlement_status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '结算状态',
`is_paid` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否支付',
`account` varchar(255) NOT NULL DEFAULT '' COMMENT '支付账户',
`transit_id` varchar(20) NOT NULL DEFAULT '' COMMENT '交易流水号',
`add_time` int(11) NOT NULL DEFAULT '0',
`pay_time` int(11) NOT NULL DEFAULT '0' COMMENT '流水时间',
`customer_id` varchar(255) NOT NULL DEFAULT '',
`servicer_id` int(11) NOT NULL DEFAULT '0',
`waybill_number` varchar(20) NOT NULL DEFAULT '',
`city` varchar(255) NOT NULL COMMENT '城市',
`weight` double(10,2) NOT NULL COMMENT '重量',
`date` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1566 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for zcharge_first
-- ----------------------------
DROP TABLE IF EXISTS `zcharge_first`;
CREATE TABLE `zcharge_first` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`seller_id` int(11) NOT NULL,
`seller_name` varchar(255) NOT NULL,
`class_id` int(11) NOT NULL,
`class_name` varchar(255) NOT NULL,
`storage_number` int(11) NOT NULL,
`storage_charge` float(10,4) NOT NULL DEFAULT '0.0000',
`add_time` int(11) NOT NULL DEFAULT '0',
`date` date NOT NULL,
`money_type` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1海运费、2空运费',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for zcharge_storage
-- ----------------------------
DROP TABLE IF EXISTS `zcharge_storage`;
CREATE TABLE `zcharge_storage` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`seller_id` int(11) NOT NULL,
`seller_name` varchar(255) NOT NULL,
`class_id` int(11) NOT NULL,
`class_name` varchar(255) NOT NULL COMMENT '冗余字段',
`storage_number` int(11) NOT NULL,
`storage_charge` float(10,4) NOT NULL DEFAULT '0.0000',
`add_time` int(11) NOT NULL DEFAULT '0',
`date` date NOT NULL COMMENT 'wms提供',
`money_type` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1收货上架费、2库内操作费、3库内仓储费、4退货处理费、5返厂处理费',
`order_sn` varchar(255) NOT NULL COMMENT '可能没有',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for zkili_goods
-- ----------------------------
DROP TABLE IF EXISTS `zkili_goods`;
CREATE TABLE `zkili_goods` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Id',
`goods_id` int(10) unsigned NOT NULL COMMENT '商品id',
`sku_code` varchar(100) NOT NULL COMMENT 'Sku编码',
`goods_name` varchar(200) NOT NULL COMMENT '商品名称',
`Seller_id` int(10) unsigned NOT NULL COMMENT '所属商家id',
`goods_barcode` varchar(100) DEFAULT NULL COMMENT '商品条码',
`out_goods_barcode` varchar(100) DEFAULT NULL COMMENT '外部商品条码:适用于kilimall外部商品,进入kilimall后对应关系,可以存储产品本身S/N或IMEI号',
`gc_id` int(10) unsigned NOT NULL COMMENT '商品分类id',
`gc_name` varchar(100) NOT NULL COMMENT '商品分类名称',
`goods_warehouse` varchar(50) NOT NULL COMMENT '所属仓库',
`goods_state` tinyint(3) unsigned DEFAULT NULL COMMENT '商品状态 0下架,1正常,10违规(禁售)',
`pla_class_id` int(15) unsigned NOT NULL COMMENT '平台分类id',
`pla_class_name` varchar(200) DEFAULT NULL COMMENT '平台分类名称',
`goods_exportprice` decimal(10,2) DEFAULT NULL COMMENT '商品出口申报价值',
`is_insured` tinyint(2) unsigned DEFAULT NULL COMMENT '是否保价',
`insured_money` decimal(10,2) DEFAULT NULL COMMENT '保价额度',
`goods_importprice` decimal(10,2) DEFAULT NULL COMMENT '商品进口申报价值',
`goods_marketprice` decimal(10,2) DEFAULT NULL COMMENT '商品零售价格',
`goods_addtime` int(10) unsigned NOT NULL COMMENT '创建日期',
`bi_updated_time` varchar(50) DEFAULT NULL COMMENT '修改人',
`create_user` varchar(50) NOT NULL COMMENT '创建人',
`goods_update_time` int(10) unsigned DEFAULT NULL COMMENT '修改日期',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
--- URI Online Judge SQL
--- Copyright URI Online Judge
--- www.urionlinejudge.com.br
--- Problem 2624
SELECT COUNT (DISTINCT customers.city) AS count FROM customers;
|
SELECT wait_type, d__wait_s, percentage = cast(100.0 * d__wait_s / SUM(d__wait_s) OVER() as decimal(5, 2))
FROM tempdb..tbl_wait_stats_1 curr (nolock)
left join (
select b_exists = 1, b_cs = checksum(_wait_s), b_wait_type = wait_type, b__wait_s = _wait_s
from tempdb..tbl_wait_stats_2 (nolock)
) prev on prev.b_wait_type = curr.wait_type
cross apply (select
d__wait_s = abs(isnull(_wait_s, 0) - isnull(b__wait_s, 0))
) d
where b_cs is null or b_cs <> checksum(_wait_s)
order by percentage desc |
/*
CREAR BASE DE DATOS PATRON desafio3-tuNombre-tuApellido-3digitos
*/
DROP DATABASE IF EXISTS "desafio3-marco-contreras-911";
CREATE DATABASE "desafio3-marco-contreras-911";
/*
CREAR TABLA USUARIOS
Donde:
- El id es serial.
- El rol es un varchar que puede ser "administrador" o "usuario", no es necesario limutarlo
- El resto de los campos definirlos utilizando el mejor criterio. */
DROP TABLE IF EXISTS usuarios;
CREATE TABLE usuarios(
id SERIAL PRIMARY KEY,
email VARCHAR(40) NOT NULL,
nombre VARCHAR(40) NOT NULL,
apellido VARCHAR(40) NOT NULL,
rol VARCHAR(20),
CHECK (rol = 'administrador' OR rol = 'usuario')
);
/*
Agregar 5 usuarios en la base de datos, debe haber al menos un usuario con el rol de administrador */
INSERT INTO usuarios (email, nombre, apellido, rol)
VALUES
('marco@gmail.com', 'marco', 'conteras', 'administrador'),
('pedro@gmail.com', 'pedro', 'villarroel', 'usuario'),
('javier@gmail.com', 'javier', 'vargas', 'usuario'),
('luis@gmail.com', 'luis', 'rojas', 'usuario'),
('fabian@gmail.com', 'fabian', 'aguirre', 'usuario');
-- SELECT * from usuarios;
/*
CREAR TABLA POSTS
Donde:
- fecha_creación y fecha_actualización son de tipo timestamp.
- destacado es un boolean.
- usuario_id es un bigint y es utilizado para conectar con el usuario que escribió el post.
- título es un varchar.
- contenido es un tipo text. */
DROP TABLE IF EXISTS posts;
CREATE TABLE posts(
id SERIAL PRIMARY KEY,
título VARCHAR(50) NOT NULL,
contenido TEXT,
fecha_creación TIMESTAMP,
fecha_actualización TIMESTAMP,
destacado BOOLEAN,
usuario_id BIGINT
);
/*
Ingresar 5 posts:
- El post con id 1 y 2 deben pertenecer al usuario administrador.
- El post 3 y 4 asignarlo al usuario que prefieras (no puede ser el administrador)
- El post 5 no debe tener usuario_id asignado */
INSERT INTO posts (título, contenido, fecha_creación, fecha_actualización, destacado, usuario_id)
VALUES
('instalar postgres en ubuntu', 'Lorem Ipsum Content1 ....','2019-03-02'::timestamp, '2019-03-02'::timestamp, 't', 1),
('instalar postgres en fedora', 'Lorem Ipsum Content2 ....','2020-03-02'::timestamp, '2020-03-02'::timestamp, 't', 1),
('conectarse desde psql', 'Lorem Ipsum Content3 ....','2021-04-06'::timestamp, '2021-04-06'::timestamp, 't', 2),
('crear una base de datos en postgres', 'Lorem Ipsum Content3 ....','2021-05-22'::timestamp, '2021-05-22'::timestamp, 'f', 3),
('meta-comandos de psql', 'Lorem Ipsum Content3 ....','2023-01-01'::timestamp, '2023-01-01'::timestamp, 'f', NULL);
-- SELECT * FROM posts;
/*
CREAR TABLA COMENTARIOS
Donde:
- fecha_creación es un timestamp.
- usuario_id es un bigint para conectarlo con el usuario que escribió el comentario.
- post_id es un bigint que se utilizará para conectarlo con el id de la tabla post.
- contenido es un tipo text. */
DROP TABLE IF EXISTS comentarios;
CREATE TABLE comentarios(
id SERIAL PRIMARY KEY,
contenido TEXT NOT NULL,
fecha_creación TIMESTAMP,
usuario_id BIGINT,
post_id BIGINT
);
/*
Ingresar 5 comentarios:
Los comentarios con id 1, 2 y 3 deben estar asociado al post 1, a los usuarios 1, 2 y 3 respectivamente.
Los comentarios 4 y 5 deben estar asociado al post 2, a los usuarios 1 y 2 respectivamente.*/
INSERT INTO comentarios (contenido, fecha_creación, usuario_id, post_id)
VALUES
('Comentario Lorem Ipsum Content1 ....','2019-03-02'::timestamp, 1, 1),
('Comentario Lorem Ipsum Content2 ....','2019-03-03'::timestamp, 2, 1),
('Comentario Lorem Ipsum Content3 ....','2019-03-04'::timestamp, 3, 1),
('Comentario Lorem Ipsum Content4 ....','2020-03-02'::timestamp, 1, 2),
('Comentario Lorem Ipsum Content5 ....','2020-03-03'::timestamp, 2, 2);
-- SELECT * FROM comentarios; |
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema EnglishGame_BD
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema EnglishGame_BD
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `EnglishGame_BD` DEFAULT CHARACTER SET utf8 ;
USE `EnglishGame_BD` ;
-- -----------------------------------------------------
-- Table `EnglishGame_BD`.`subject`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `EnglishGame_BD`.`subject` (
`id` INT NOT NULL,
`name` VARCHAR(100) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `EnglishGame_BD`.`question`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `EnglishGame_BD`.`question` (
`id` INT NOT NULL,
`firstPart` VARCHAR(100) NOT NULL,
`secondPart` VARCHAR(100) NOT NULL,
`type` VARCHAR(5) NOT NULL,
`subject_id` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_question_subject_idx` (`subject_id` ASC),
CONSTRAINT `fk_question_subject`
FOREIGN KEY (`subject_id`)
REFERENCES `EnglishGame_BD`.`subject` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `EnglishGame_BD`.`answer`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `EnglishGame_BD`.`answer` (
`id` INT NOT NULL,
`content` VARCHAR(100) NOT NULL,
`question_id` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_answer_question1_idx` (`question_id` ASC),
CONSTRAINT `fk_answer_question1`
FOREIGN KEY (`question_id`)
REFERENCES `EnglishGame_BD`.`question` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `EnglishGame_BD`.`possibleAnswer`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `EnglishGame_BD`.`possibleAnswer` (
`id` INT NOT NULL,
`content` VARCHAR(100) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `EnglishGame_BD`.`word`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `EnglishGame_BD`.`word` (
`id` INT NOT NULL,
`word` VARCHAR(100) NOT NULL,
`traslation` VARCHAR(100) NOT NULL,
`question_id` INT NULL,
`possibleAnswer_id` INT NULL,
`answer_id` INT NULL,
PRIMARY KEY (`id`),
INDEX `fk_word_question1_idx` (`question_id` ASC),
INDEX `fk_word_possibleAnswer1_idx` (`possibleAnswer_id` ASC),
INDEX `fk_word_answer1_idx` (`answer_id` ASC),
CONSTRAINT `fk_word_question1`
FOREIGN KEY (`question_id`)
REFERENCES `EnglishGame_BD`.`question` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_word_possibleAnswer1`
FOREIGN KEY (`possibleAnswer_id`)
REFERENCES `EnglishGame_BD`.`possibleAnswer` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_word_answer1`
FOREIGN KEY (`answer_id`)
REFERENCES `EnglishGame_BD`.`answer` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `EnglishGame_BD`.`question_possibleAnswer`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `EnglishGame_BD`.`question_possibleAnswer` (
`question_id` INT NOT NULL,
`possibleAnswer_id` INT NOT NULL,
PRIMARY KEY (`question_id`, `possibleAnswer_id`),
INDEX `fk_question_possibleAnswer_possibleAnswer1_idx` (`possibleAnswer_id` ASC),
INDEX `fk_question_possibleAnswer_question1_idx` (`question_id` ASC),
CONSTRAINT `fk_question_possibleAnswer_question1`
FOREIGN KEY (`question_id`)
REFERENCES `EnglishGame_BD`.`question` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_question_possibleAnswer_possibleAnswer1`
FOREIGN KEY (`possibleAnswer_id`)
REFERENCES `EnglishGame_BD`.`possibleAnswer` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
|
DROP TABLE IF EXISTS `usermedicalhistories`;
CREATE TABLE `usermedicalhistories` (
`id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`medicalProblems` VARCHAR(70) DEFAULT '',
`medication` VARCHAR(70) DEFAULT '',
`allergies` VARCHAR(70) DEFAULT '',
`userid` INT DEFAULT NULL,
`createdat` DATETIME,
`updatedat` DATETIME,
`deletedat` DATETIME,
CONSTRAINT `FK_usermedicalhistories_users` FOREIGN KEY (`userid`) REFERENCES users(`id`)
);
|
create procedure mERP_SP_canupdateFileVersion @Filename nvarchar(4000),@Fileversion nvarchar(25)
AS
BEGIN
--If Max of Version number is not equal to file recovered then don't receover the file.
if((select max(cast(replace(isnull(VersionNumber,''),'.','')as int))from tbl_mERP_Fileinfo where filename = @Filename)<>replace(isnull(@Fileversion,''),'.',''))
Select 0
else
Select 1
END
|
SELECT 'FLYING' AS flight_state,
leg_id,
Substr(leg_id, 17) AS msn,
'' AS start_time,
'' AS end_time,
dep_city,
arr_city,
'' AS flight_no
FROM bombardier.servs_flight_history
WHERE Substr(leg_id, 17) = ?
AND phase IN ( 'OUT', 'ON', 'OFF' )
ORDER BY leg_id DESC
LIMIT 1 |
/*
Write an SQL query to find the person_name of the last person who will fit in the elevator without exceeding the weight limit. It is guaranteed that the person who is first in the queue can fit in the elevator.
Queue table
+-----------+-------------------+--------+------+
| person_id | person_name | weight | turn |
+-----------+-------------------+--------+------+
| 5 | George Washington | 250 | 1 |
| 3 | John Adams | 350 | 2 |
| 6 | Thomas Jefferson | 400 | 3 |
| 2 | Will Johnliams | 200 | 4 |
| 4 | Thomas Jefferson | 175 | 5 |
| 1 | James Elephant | 500 | 6 |
+-----------+-------------------+--------+------+
Result table
+-------------------+
| person_name |
+-------------------+
| Thomas Jefferson |
+-------------------+
Queue table is ordered by turn in the example for simplicity.
In the example George Washington(id 5), John Adams(id 3) and Thomas Jefferson(id 6) will enter the elevator as their weight sum is 250 + 350 + 400 = 1000.
Thomas Jefferson(id 6) is the last person to fit in the elevator because he has the last turn in these three people.
*/
CREATE TABLE Queue
(
person_id INT,
person_name VARCHAR(512),
weight INT,
turn INT
);
INSERT INTO Queue (person_id, person_name, weight , turn) VALUES
('5', 'George Washington', '250', '1'),
('3', 'John Adams', '350', '2'),
('6', 'Thomas Jefferson', '400', '3'),
('2', 'Will Johnliams', '200', '4'),
('4', 'Thomas Jefferson', '175', '5'),
('1', 'James Elephant', '500', '6');
SELECT person_name
from (
select *
, sum(weight) over(ORDER BY turn ROWS UNBOUNDED PRECEDING) weight_now
FROM Queue
) a where weight_now <= 1000
order by weight_now desc
limit 1;
select person_name from Queue last_person
where (select sum(weight) from Queue where turn <= last_person.turn) <= 1000
order by turn desc limit 1;
|
USE `user_schema`;
DROP procedure IF EXISTS `create_user_table`;
DELIMITER $$
USE `user_schema`$$
CREATE DEFINER=`root`@`%` PROCEDURE `create_user_table`()
BEGIN
CREATE TABLE IF NOT EXISTS `user` (
`user_id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
`email` VARCHAR(100),
`mobile` CHAR(11) NOT NULL,
`flat_number` VARCHAR(50) NOT NULL,
`address_line_one` VARCHAR(100),
`address_line_two` VARCHAR(100),
`city` VARCHAR(30) NOT NULL,
`state` VARCHAR(30) NOT NULL,
`pincode` CHAR(7) NOT NULL,
PRIMARY KEY (`user_id`)
);
END$$
DELIMITER ; |
insert into Groups
(id, name) values
(1, 'M3438'),
(2, 'M3439');
insert into Students
(id, name, group_id) values
(1, 'Nikita Kaberov', 1),
(2, 'Dina Ermilova', 2),
(3, 'Dmitry Yakutov', 2);
insert into Lecturers
(id, name) values
(1, 'Georgiy Korneev'),
(2, 'Andrew Stankevich');
insert into Courses
(id, name) values
(1, 'databases'),
(3, 'geometry'),
(2, 'discret math');
insert into Teaches
(course_id, lecturer_id, group_id) values
(1, 1, 1),
(1, 1, 2),
(2, 2, 1),
(2, 2, 2);
insert into Marks
(value, student_id, course_id) values
(5, 1, 1),
(4, 1, 2),
(3, 2, 1),
(4, 2, 2); |
-- MySQL dump 10.13 Distrib 5.5.9, for Win32 (x86)
--
-- Host: localhost Database: gerenciadorma
-- ------------------------------------------------------
-- Server version 5.1.56-community
/*!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 */;
--
-- Current Database: `gerenciadorma`
--
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `gerenciadorma` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `gerenciadorma`;
--
-- Table structure for table `carta`
--
DROP TABLE IF EXISTS `carta`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `carta` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`tpCarta` varchar(50) NOT NULL,
`descricao` tinytext NOT NULL,
`idStatus` int(10) NOT NULL,
`idDestinatario` int(10) NOT NULL,
`idModelo` int(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_carta_statuscarta1` (`idStatus`),
KEY `fk_carta_pessoa1` (`idDestinatario`),
KEY `fk_carta_modelocarta1` (`idModelo`),
CONSTRAINT `fk_carta_statuscarta1` FOREIGN KEY (`idStatus`) REFERENCES `statuscarta` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_carta_pessoa1` FOREIGN KEY (`idDestinatario`) REFERENCES `pessoa` (`idPessoa`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_carta_modelocarta1` FOREIGN KEY (`idModelo`) REFERENCES `modelocarta` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `carta`
--
LOCK TABLES `carta` WRITE;
/*!40000 ALTER TABLE `carta` DISABLE KEYS */;
/*!40000 ALTER TABLE `carta` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `endereco`
--
DROP TABLE IF EXISTS `endereco`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `endereco` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`logradouro` varchar(50) NOT NULL,
`bairro` varchar(50) NOT NULL,
`cidade` varchar(50) NOT NULL,
`estado` varchar(50) NOT NULL,
`numero` int(5) NOT NULL,
`complemento` varchar(20) DEFAULT NULL,
`cep` varchar(9) NOT NULL,
`latitude` double NOT NULL,
`longitude` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `endereco`
--
LOCK TABLES `endereco` WRITE;
/*!40000 ALTER TABLE `endereco` DISABLE KEYS */;
/*!40000 ALTER TABLE `endereco` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `modelocarta`
--
DROP TABLE IF EXISTS `modelocarta`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `modelocarta` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`nome` varchar(50) DEFAULT NULL,
`descricao` tinytext NOT NULL,
`nmArquivo` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `modelocarta`
--
LOCK TABLES `modelocarta` WRITE;
/*!40000 ALTER TABLE `modelocarta` DISABLE KEYS */;
/*!40000 ALTER TABLE `modelocarta` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `pessoa`
--
DROP TABLE IF EXISTS `pessoa`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pessoa` (
`idPessoa` int(10) NOT NULL AUTO_INCREMENT,
`nome` varchar(50) NOT NULL,
`dtNascimento` date NOT NULL,
`rg` varchar(12) NOT NULL,
`telefone` int(10) DEFAULT NULL,
`celular` int(11) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`tpPessoa` varchar(20) NOT NULL,
`login` varchar(20) DEFAULT NULL,
`senha` varchar(50) DEFAULT NULL,
`ministerio` varchar(50) DEFAULT NULL,
`membroPrincipal` int(10) NOT NULL,
`endereco` int(10) NOT NULL,
`sexo` varchar(15) NOT NULL,
PRIMARY KEY (`idPessoa`),
KEY `fk_pessoa_endereco` (`endereco`),
CONSTRAINT `fk_pessoa_endereco` FOREIGN KEY (`endereco`) REFERENCES `endereco` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `pessoa`
--
LOCK TABLES `pessoa` WRITE;
/*!40000 ALTER TABLE `pessoa` DISABLE KEYS */;
/*!40000 ALTER TABLE `pessoa` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `statuscarta`
--
DROP TABLE IF EXISTS `statuscarta`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `statuscarta` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`estado` varchar(20) NOT NULL,
`dtEstado` date NOT NULL,
`descricao` tinytext NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `statuscarta`
--
LOCK TABLES `statuscarta` WRITE;
/*!40000 ALTER TABLE `statuscarta` DISABLE KEYS */;
/*!40000 ALTER TABLE `statuscarta` 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 2013-01-02 16:26:05
|
use namjunwebdb;
SELECT bmsTitle, bmsSubtitle, bmstableType,
bmstableNorDiff, bmstableInDiff, bmstableLNInDiff,
bmsTOTAL, bmsNotes, bmsMD5, bmsMirrorURL, bmsYoutubeURL
FROM bmsfile, bmstable
WHERE bmsfile.bmsNo = bmstable.bmstableNo
and bmsPlayStyle = 2;
select * from bmsevent;
select * from bmsfile;
select * from bmstable;
|
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
CREATE TABLE `entry` (
`user_id` int(10) NOT NULL,
`fullname` varchar(100) NOT NULL,
`text` varchar(100) NOT NULL,
`publish_date` date NOT NULL,
`email` varchar(100) NOT NULL,
`title` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `books` (`user_id`, `fullname`, `text`,`publish_date`, `email`, `title`) VALUES
(20045, 'karanbagga', 'uidgbdjdw', '555', 'bagga@gmail.com', 'fuhe'),
(20046, 'tananbagga', 'jebfhqoiwlifwh', '554', 'tanan@gmail.com', 'hcidf'),
(20048, 'manjubagga', 'jqwifhqwoifhwihi', '22', 'mannu@gmail.com', 'iudwu');
ALTER TABLE `entry`
ADD PRIMARY KEY (`user_id`);
|
use ccweb;
create table Users
(
email varchar(128) not null,
password varchar(256) not null,
firstName varchar(100) null,
lastName varchar(100) null,
account_created varchar(100) null,
account_updated varchar(100) null,
id varchar(256) not null ,
constraint users_pk
unique (id)
);
create table Recipie
(
id varchar(256) not null primary key unique ,
created_ts varchar(100) null,
updated_ts varchar(100) null,
author_id varchar(256) null,
cook_time_in_min int null,
prep_time_in_min int null,
total_time_in_min int null,
title varchar(100) null,
cusine varchar(100) null,
servings int null
);
create table Steps
(
position int not null,
items varchar(256) null,
recipie_id varchar(256) not null
);
create table NutritionInformation
(
recipie_id varchar(256) not null,
calories int null,
cholesterol_in_mg float null,
sodium_in_mg int null,
carbohydrates_in_grams float null,
protein_in_grams float null
--foreign key(recipie_id) references Recipie(id);
);
create table Image
(
id varchar(256) not null,
url nvarchar(1024) null,
--foreign key (id) references Recipie(id)
);
create table Ingredients
(
recipie_id varchar(256) ,
content varchar(256)
) |
USE desi_loja;
SELECT p.id_produto, p.nome, pi.quantidade
FROM produto p
LEFT JOIN pedido_item pi
ON pi.quantidade
ORDER BY p.id_produto;
/*Utilizar a base desi_loja → Utilize o comando USE
Utilizar as tabelas produto e pedido_item
Retornar como resultado da consulta com o OUTER JOIN todos os produtos da tabela produto com a quantidade deles que foi utilizada nos pedidos, caso tenha.
As colunas que devem ser mostradas no SELECT seriam produto.id_produto, produto.nome e pedido_item.quantidade.*/
|
DROP TABLE IF EXISTS `cbg_huwelijk`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cbg_huwelijk` (
`id` int(11) unsigned NOT NULL,
`Bruidegom_voornaam` VARCHAR( 100) DEFAULT NULL,
`Bruidegom_patroniem` VARCHAR( 100) DEFAULT NULL,
`Bruidegom_tussenvoegsel` VARCHAR( 30) DEFAULT NULL,
`Bruidegom_achternaam` VARCHAR( 100) DEFAULT NULL,
`Bruidegom_woonplaats` VARCHAR( 120) DEFAULT NULL,
`Bruidegom_leeftijd_literal` VARCHAR( 300) DEFAULT NULL,
`Bruidegom_leeftijd_Jaar` VARCHAR( 10) DEFAULT NULL,
`Bruidegom_datum_geboorte_literal` VARCHAR( 300) DEFAULT NULL,
`Bruidegom_datum_geboorte_YYYY` VARCHAR( 50) DEFAULT NULL,
`Bruidegom_datum_geboorte_MM` VARCHAR( 50) DEFAULT NULL,
`Bruidegom_datum_geboorte_DD` VARCHAR( 50) DEFAULT NULL,
`Bruidegom_geboorteplaats` VARCHAR( 120) DEFAULT NULL,
`Bruidegom_beroep1` VARCHAR( 200) DEFAULT NULL,
`Bruidegom_beroep2` VARCHAR( 200) DEFAULT NULL,
`Bruidegom_vader_voornaam` VARCHAR( 100) DEFAULT NULL,
`Bruidegom_vader_patroniem` VARCHAR( 100) DEFAULT NULL,
`Bruidegom_vader_tussenvoegsel` VARCHAR( 30) DEFAULT NULL,
`Bruidegom_vader_achternaam` VARCHAR( 100) DEFAULT NULL,
`Bruidegom_vader_beroep1` VARCHAR( 200) DEFAULT NULL,
`Bruidegom_vader_beroep2` VARCHAR( 200) DEFAULT NULL,
`Bruidegom_moeder_voornaam` VARCHAR( 100) DEFAULT NULL,
`Bruidegom_moeder_patroniem` VARCHAR( 100) DEFAULT NULL,
`Bruidegom_moeder_tussenvoegsel` VARCHAR( 30) DEFAULT NULL,
`Bruidegom_moeder_achternaam` VARCHAR( 100) DEFAULT NULL,
`Bruidegom_moeder_beroep1` VARCHAR( 200) DEFAULT NULL,
`Bruidegom_moeder_beroep2` VARCHAR( 200) DEFAULT NULL,
`Bruid_voornaam` VARCHAR( 100) DEFAULT NULL,
`Bruid_patroniem` VARCHAR( 100) DEFAULT NULL,
`Bruid_tussenvoegsel` VARCHAR( 30) DEFAULT NULL,
`Bruid_achternaam` VARCHAR( 100) DEFAULT NULL,
`Bruid_woonplaats` VARCHAR( 120) DEFAULT NULL,
`Bruid_leeftijd_literal` VARCHAR( 300) DEFAULT NULL,
`Bruid_leeftijd_Jaar` VARCHAR( 10) DEFAULT NULL,
`Bruid_datum_geboorte_literal` VARCHAR( 300) DEFAULT NULL,
`Bruid_datum_geboorte_YYYY` VARCHAR( 50) DEFAULT NULL,
`Bruid_datum_geboorte_MM` VARCHAR( 50) DEFAULT NULL,
`Bruid_datum_geboorte_DD` VARCHAR( 50) DEFAULT NULL,
`Bruid_geboorteplaats` VARCHAR( 120) DEFAULT NULL,
`Bruid_beroep1` VARCHAR( 200) DEFAULT NULL,
`Bruid_beroep2` VARCHAR( 200) DEFAULT NULL,
`Bruid_vader_voornaam` VARCHAR( 100) DEFAULT NULL,
`Bruid_vader_patroniem` VARCHAR( 100) DEFAULT NULL,
`Bruid_vader_tussenvoegsel` VARCHAR( 30) DEFAULT NULL,
`Bruid_vader_achternaam` VARCHAR( 100) DEFAULT NULL,
`Bruid_vader_beroep1` VARCHAR( 200) DEFAULT NULL,
`Bruid_vader_beroep2` VARCHAR( 200) DEFAULT NULL,
`Bruid_moeder_voornaam` VARCHAR( 100) DEFAULT NULL,
`Bruid_moeder_patroniem` VARCHAR( 100) DEFAULT NULL,
`Bruid_moeder_tussenvoegsel` VARCHAR( 30) DEFAULT NULL,
`Bruid_moeder_achternaam` VARCHAR( 100) DEFAULT NULL,
`Bruid_moeder_beroep1` VARCHAR( 200) DEFAULT NULL,
`Bruid_moeder_beroep2` VARCHAR( 200) DEFAULT NULL,
`Datum_huwelijk_literal` VARCHAR( 300) DEFAULT NULL,
`Datum_huwelijk_YYYY` VARCHAR( 50) DEFAULT NULL,
`Datum_huwelijk_MM` VARCHAR( 50) DEFAULT NULL,
`Datum_huwelijk_DD` VARCHAR( 50) DEFAULT NULL,
`Plaats_huwelijk` VARCHAR( 22) DEFAULT NULL,
`Datum_huwelijksaangifte_literal` VARCHAR( 300) DEFAULT NULL,
`Datum_huwelijksaangifte_YYYY` VARCHAR( 50) DEFAULT NULL,
`Datum_huwelijksaangifte_MM` VARCHAR( 50) DEFAULT NULL,
`Datum_huwelijksaangifte_DD` VARCHAR( 50) DEFAULT NULL,
`Datum_echtscheiding_literal` VARCHAR( 300) DEFAULT NULL,
`Datum_echtscheiding_YYYY` VARCHAR( 50) DEFAULT NULL,
`Datum_echtscheiding_MM` VARCHAR( 50) DEFAULT NULL,
`Datum_echtscheiding_DD` VARCHAR( 50) DEFAULT NULL,
`Gemeentenaam` VARCHAR( 100) DEFAULT NULL,
`Akte_datum_literal` VARCHAR( 300) DEFAULT NULL,
`Akte_datum_YYYY` VARCHAR( 50) DEFAULT NULL,
`Akte_datum_MM` VARCHAR( 50) DEFAULT NULL,
`Akte_datum_DD` VARCHAR( 50) DEFAULT NULL,
`Bronsoort` VARCHAR( 50) DEFAULT NULL,
`Plaats_instelling` VARCHAR( 120) DEFAULT NULL,
`Naam_instelling` VARCHAR( 100) DEFAULT NULL,
`Toegangsnummer` VARCHAR( 20) DEFAULT NULL,
`Inventarisnummer` VARCHAR( 10) DEFAULT NULL,
`Aktenummer` VARCHAR( 30) DEFAULT NULL,
`Scan_nummer_1` VARCHAR( 50) DEFAULT NULL,
`Scan_uri_1` VARCHAR( 200) DEFAULT NULL,
`Scan_nummer_2` VARCHAR( 50) DEFAULT NULL,
`Scan_uri_2` VARCHAR( 200) DEFAULT NULL,
`Scan_nummer_3` VARCHAR( 50) DEFAULT NULL,
`Scan_uri_3` VARCHAR( 200) DEFAULT NULL,
`Scan_nummer_4` VARCHAR( 50) DEFAULT NULL,
`Scan_uri_4` VARCHAR( 200) DEFAULT NULL,
`Scan_nummer_5` VARCHAR( 50) DEFAULT NULL,
`Scan_uri_5` VARCHAR( 200) DEFAULT NULL,
`Scan_nummer_6` VARCHAR( 50) DEFAULT NULL,
`Scan_uri_6` VARCHAR( 200) DEFAULT NULL,
`Scan_nummer_7` VARCHAR( 50) DEFAULT NULL,
`Scan_uri_7` VARCHAR( 200) DEFAULT NULL,
`Scan_nummer_8` VARCHAR( 50) DEFAULT NULL,
`Scan_uri_8` VARCHAR( 200) DEFAULT NULL,
`Scan_nummer_9` VARCHAR( 50) DEFAULT NULL,
`Scan_uri_9` VARCHAR( 200) DEFAULT NULL,
`Scan_nummer_10` VARCHAR( 50) DEFAULT NULL,
`Scan_uri_10` VARCHAR( 200) DEFAULT NULL,
`Mutatiedatum` VARCHAR( 50) DEFAULT NULL,
`Scan_URI_Origineel` VARCHAR( 200) DEFAULT NULL,
`RecordGUID` VARCHAR( 80) DEFAULT NULL,
`Opmerking` VARCHAR(2048) DEFAULT NULL,
`AkteSoort` VARCHAR( 200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
/**
* Author: wesley
* Created: Aug 15, 2019
*/
-- drop tables id exists
DROP TABLE IF EXISTS tb_produto;
DROP TABLE IF EXISTS tb_categoria;
-- create database tb_categoria
CREATE TABLE tb_categoria(
id SERIAL PRIMARY KEY,
nome varchar(50)
);
-- create database tb_produto
CREATE TABLE tb_produto(
id SERIAL PRIMARY KEY,
id_categoria integer NOT NULL,
nome varchar(80),
valorunitario double precision,
CONSTRAINT fk_produto_categoria FOREIGN KEY (id_categoria)
REFERENCES tb_categoria(id)
);
-- insert data into database tb_categoria
INSERT INTO tb_categoria (nome) VALUES ('Informática');
INSERT INTO tb_categoria (nome) VALUES ('Eletônicos');
INSERT INTO tb_categoria (nome) VALUES ('Papelaria');
INSERT INTO tb_categoria (nome) VALUES ('Beleza');
INSERT INTO tb_categoria (nome) VALUES ('Livros');
INSERT INTO tb_categoria (nome) VALUES ('Perfumaria');
INSERT INTO tb_categoria (nome) VALUES ('Móveis');
INSERT INTO tb_categoria (nome) VALUES ('Celulares');
|
CREATE DEFINER=`root`@`localhost` TRIGGER `trigger_lerning`.`PersonInsertAfter` AFTER INSERT ON trigger_lerning.person FOR EACH ROW
BEGIN
SET @personID = '';
SET @FN = '';
SET @LN = '';
SET @MN = '';
SELECT TLP.person_id, TLP.firstname, TLP.lastname, TLP.middlename
INTO @personID, @FN, @LN, @MN FROM trigger_lerning.person TLP WHERE person_id = (SELECT MAX(P.person_id) FROM trigger_lerning.person P );
INSERT INTO trigger_lerning.person_log ( log_message, log_datetime )
VALUES ( concat('INSERT AFTER person_id', @personID, ' - ', @FN, ' ', @LN, ' ', @MN), NOW() );
END; |
USE gyak11;
CREATE TABLE Tulajdonos(TKód INT(4) Primary Key, Név Varchar(20) Not Null, Város Varchar(20));
CREATE TABLE Autó (Rendszám Char(7) Primary Key, Típus Varchar(25) Not Null , Szín Varchar(15), Kor int(2), Ár INT(8), Tulaj int(4), Foreign key(Tulaj) REFERENCES Tulajdonos(TKód));
CREATE TABLE Kategoria (Knév VARCHAR(12), AlsóHP INT(4), FelsőHP Int(4));
|
UPDATE `users`
SET
`username` = "Usman A Khan",
`email` = "usmanakhan@yahoo.com"
WHERE `id` IN (1, 2) |
# add a somatic_status column to source
ALTER TABLE source ADD COLUMN somatic_status ENUM ('germline','somatic','mixed') DEFAULT 'germline';
UPDATE source SET somatic_status = 'somatic' WHERE name = 'COSMIC';
UPDATE source SET somatic_status = 'mixed' WHERE name = 'dbSNP';
INSERT INTO meta (species_id, meta_key, meta_value) VALUES (NULL,'patch','patch_61_62_o.sql|add a somatic_status columns to source');
|
USE ims;
CREATE TABLE `product_vendor` (
`productID` int(10) unsigned NOT NULL,
`VendorID` int(10) unsigned NOT NULL,
`AverageLeadTime` float DEFAULT NULL,
`StandardPrice` float DEFAULT NULL,
`LastReceiptCost` float DEFAULT NULL,
`LastReceiptDate` date DEFAULT NULL,
`MinOrderQty` float DEFAULT NULL,
`MaxOrderQty` float DEFAULT NULL,
`CurrentOrderedQty` float DEFAULT NULL,
PRIMARY KEY (`productID`,`VendorID`),
KEY `PV_product_FK_idx` (`productID`),
KEY `PV_Vendor_FK_idx` (`VendorID`),
CONSTRAINT `PV_product_FK` FOREIGN KEY (`productID`) REFERENCES `products` (`ProductID`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `PV_Vendor_FK` FOREIGN KEY (`VendorID`) REFERENCES `vendor` (`VendorID`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
|
CREATE TABLE `fail_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`mid` int(11) DEFAULT NULL,
`response_code` int(5) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
|
CREATE DATABASE IF NOT EXISTS `nhanvien` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `nhanvien`;
-- MySQL dump 10.13 Distrib 8.0.26, for Win64 (x86_64)
--
-- Host: localhost Database: nhanvien
-- ------------------------------------------------------
-- Server version 8.0.26
/*!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 */;
/*!50503 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 `employee`
--
DROP TABLE IF EXISTS `employee`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `employee` (
`id` varchar(50) NOT NULL,
`name` varchar(225) DEFAULT NULL,
`age` int DEFAULT NULL,
`phone` varchar(50) DEFAULT NULL,
`email` varchar(225) DEFAULT NULL,
`basic_salary` float DEFAULT NULL,
`overtime_hour` int DEFAULT NULL,
`number_of_bugs` int DEFAULT NULL,
`employee_type` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `employee`
--
LOCK TABLES `employee` WRITE;
/*!40000 ALTER TABLE `employee` DISABLE KEYS */;
INSERT INTO `employee` VALUES ('13ca2f48-6a6d-4a51-810c-d59ed201c3c2','vavaa',233,NULL,'advav',2300,23,NULL,'DEV'),('d8a664f6-990a-47eb-9c4b-9b94af3408ed','vvv',12,'234234','ewr',2000,4,NULL,'DEV');
/*!40000 ALTER TABLE `employee` 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 2021-10-25 16:23:50
|
-- 숫자 관련 함수
-- round(): 반올림
select 1234.5678, round(1234.5678),
round(1234.5678, 1), round(1234.5678, 2),
round(1234.5678, -1), round(1234.5678, -2)
from dual;
-- trunc(): 버림. 자름(truncate)
select 1234.5678, trunc(1234.5678),
trunc(1234.5678, 1), trunc(1234.5678, 2),
trunc(1234.5678, -1), trunc(1234.5678, -2)
from dual;
-- floor(), ceil()
select floor(3.14), ceil(3.14),
floor(-3.14), ceil(-3.14),
trunc(-3.14)
from dual;
-- null 처리 함수:
-- nvl(컬럼, null을 대체할 값)
-- nvl2(컬럼, null이 아닐 때 대체할 값, null일 때 대체할 값)
select comm, nvl(comm, -1), nvl2(comm, 'YES', 'NO')
from emp;
select comm, nvl2(comm, comm, -1) from emp;
-- emp 테이블에서 모든 사원들의 1년 연봉을 검색
-- 연봉 = sal * 12 + comm
select sal, comm, sal * 12 + nvl(comm, 0) as annual_sal
from emp;
-- 집계 함수, 다중행 함수(multi-row function):
-- 여러개의 행(row)을 집계해서 하나의 결과값을 리턴하는 함수.
-- 예: 합계(sum), 평균(avg), 최댓값(max), 최솟값(min),
-- 분산(variance), 표준편차(stddev), 중앙값(median)
select sum(sal), round(avg(sal), 1), max(sal), min(sal),
round(variance(sal), 1), round(stddev(sal), 1), median(sal)
from emp;
select sal from emp order by sal;
-- count(): 레코드(행, row)의 개수
select count(*) from emp; -- 테이블의 row 개수
select count(sal), count(comm), count(mgr) from emp;
-- 각 컬럼의 NULL이 아닌 row의 개수
-- 다중행 함수는 여러개의 행이 결과로 출력되는 변수(또는 함수)와는 함께
-- select할 수 없음!
select empno from emp; -- 결과: 14개 rows
select count(empno) from emp; -- 결과: 1개 row
-- select empno, count(empno) from emp; -- 오류(error) 발생
-- 10번 부서 사원들의 급여 평균, 최댓값, 최솟값, 표준편차를 출력
-- 소수점은 1자리까지만 출력.
select sal from emp where deptno = 10;
select round(avg(sal), 1), max(sal), min(sal), round(stddev(sal), 1)
from emp
where deptno = 10;
-- 20번 부서 사원들의 급여의 평균, 최댓값, 최솟값, 표준편차
select sal from emp where deptno = 20;
select round(avg(sal), 1), max(sal), min(sal), round(stddev(sal), 1)
from emp
where deptno = 20;
-- group by
-- 각 부서별 급여의 평균, 최댓값, 최솟값을 검색
select deptno, avg(sal), max(sal), min(sal)
from emp
group by deptno;
-- 부서별 부서번호, 급여의 평균과 표준편차를 검색.
-- 소수점 이하 한자리까지 반올림으로 표현.
-- 부서번호의 오름차순으로 정렬해서 출력.
select deptno, round(avg(sal), 1), round(stddev(sal), 1)
from emp
group by deptno
order by deptno;
-- 직책(job)별 직책, 급여의 평균, 최댓값, 최솟값, 사원수를 검색.
-- 소수점 이하 한자리까지 반올림으로 표현.
-- 직책의 오름차순으로 정렬해서 출력.
select job, round(avg(sal), 1), max(sal), min(sal), count(*)
from emp
group by job
order by job;
-- 입사 연도별 사원수, 급여 평균을 검색. 연도의 오름차순 정렬.
select hiredate, to_char(hiredate, 'YYYY') from emp;
select to_char(hiredate, 'YYYY') as HIRE_DATE,
count(*) as COUNTS,
to_char(avg(sal), '9,999.0') as AVG_SAL
from emp
group by to_char(hiredate, 'YYYY')
order by HIRE_DATE;
select to_char(1234, '9,999.0') from dual;
-- 부서별, 직책별 부서번호, 직책, 사원수, 급여 평균을 검색
-- 정렬 기준: 1) 부서번호, 2) 직책
select deptno, job, count(*), avg(sal)
from emp
group by deptno, job
order by deptno, job;
select job, deptno, count(*), avg(sal)
from emp
group by job, deptno
order by job, deptno;
-- 매니저별 사원 수 검색. 매니저 사번의 오름차순 정렬.
select mgr, count(*)
from emp
group by mgr
order by mgr;
-- 매니저별 사원 수 검색. 단, 매니저 사번이 null 아닌 경우만.
-- 매니저 사번의 오름차순 정렬.
select mgr, count(*)
from emp
where mgr is not null
group by mgr
order by mgr;
-- where 조건절은 그룹별로 묶기 전에 필터링하기 위해서 사용!
-- 부서별 부서번호, 급여 평균 검색.
-- 부서별 급여 평균이 2000 이상인 경우만 검색.
select deptno, avg(sal)
from emp
where avg(sal) >= 2000
group by deptno;
-- 오류(error) 발생:
-- 그룹별로 묶기 전에 그룹함수 avg()를 where에서 사용할 수 없음!
-- having: 그룹으로 묶은 다음 조건 검사가 필요한 경우에 사용.
select deptno, avg(sal)
from emp
group by deptno
having avg(sal) >= 2000
order by deptno;
/* SELECT 구문의 순서
select 컬럼이름, ...
from 테이블이름
where 조건 검사
group by 컬럼이름, ...
having 그룹별 조건 검사
order by 컬럼이름, ...;
*/
-- 직책별 직책, 사원수 검색. PRESIDENT는 제외.
-- 직책별 사원수가 3명 이상인 직책만 선택.
-- 직책 오름차순 정렬
select job, count(*)
from emp
where job != 'PRESIDENT'
group by job
having count(*) >= 3
order by job;
-- 연도, 부서번호, 연도별 부서별 입사한 사원수를 출력
-- 1980년은 제외
-- 사원수가 2명 이상인 경우만 출력
-- 연도 순으로 정렬해서 출력
select to_char(hiredate, 'YYYY') as YEAR, deptno, count(*)
from emp
where to_char(hiredate, 'YYYY') != '1980'
group by to_char(hiredate, 'YYYY'), deptno
having count(*) >= 2
order by YEAR;
-- 수당을 받는 사원 수와 수당을 받지 않는 사원 수를 출력.
select nvl2(comm, 'YES', 'NO'), count(*)
from emp
group by nvl2(comm, 'YES', 'NO');
|
--修改人:蒲勇军
--修改时间:2012-10-9
--修改内容:如果字段不存在则添加字段
DECLARE
VN_COUNT NUMBER;
V_STR VARCHAR2(1000);
BEGIN
select COUNT(*)
INTO VN_COUNT
from user_tab_cols
where table_name = 'AB_OPERATION' AND COLUMN_NAME = 'ATTACHMENT';
IF VN_COUNT < 1 THEN
V_STR := ' ALTER TABLE AB_OPERATION ADD ATTACHMENT CHAR(10)';
EXECUTE IMMEDIATE V_STR;
END IF;
END;
/
|
-- phpMyAdmin SQL Dump
-- version 4.8.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Sep 08, 2019 at 12:05 PM
-- Server version: 10.1.34-MariaDB
-- PHP Version: 5.6.37
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 */;
--
-- Database: `netmanager`
--
CREATE DATABASE IF NOT EXISTS `netmanager` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `netmanager`;
-- --------------------------------------------------------
--
-- Table structure for table `main`
--
DROP TABLE IF EXISTS `main`;
CREATE TABLE `main` (
`id` int(11) NOT NULL,
`tableName` varchar(20) NOT NULL,
`lastTime` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `main`
--
INSERT INTO `main` (`id`, `tableName`, `lastTime`) VALUES
(1, 'crdplt', '2018-10-19 18:28:43'),
(2, 'exit_trans', '2018-11-09 12:51:04'),
(3, 'colltrain', '2018-09-16 21:32:57'),
(4, 'zread', '2018-09-16 21:32:58');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `main`
--
ALTER TABLE `main`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `main`
--
ALTER TABLE `main`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
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 keyspace if exists chart_development;
create keyspace chart_development with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };
drop keyspace if exists chart_test;
create keyspace chart_test with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };
|
DROP TABLE IF EXISTS `users`;
create table users (
username varchar(256),
password varchar(256),
enabled boolean
)ENGINE=MyISAM DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `authorities`;
create table authorities (
username varchar(256),
authority varchar(256)
)ENGINE=MyISAM DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `oauth_client_details`;
create table oauth_client_details (
client_id VARCHAR(256) PRIMARY KEY,
resource_ids VARCHAR(256),
client_secret VARCHAR(256),
scope VARCHAR(256),
authorized_grant_types VARCHAR(256),
web_server_redirect_uri VARCHAR(256),
authorities VARCHAR(256),
access_token_validity INTEGER,
refresh_token_validity INTEGER,
additional_information VARCHAR(4096),
autoapprove VARCHAR(256)
)ENGINE=MyISAM DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `oauth_client_token`;
create table oauth_client_token (
token_id VARCHAR(256),
token BLOB,
authentication_id VARCHAR(256),
user_name VARCHAR(256),
client_id VARCHAR(256)
)ENGINE=MyISAM DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `oauth_access_token`;
create table oauth_access_token (
token_id VARCHAR(256),
token BLOB,
authentication_id VARCHAR(256),
user_name VARCHAR(256),
client_id VARCHAR(256),
authentication BLOB,
refresh_token VARCHAR(256)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `oauth_refresh_token`;
create table oauth_refresh_token (
token_id VARCHAR(256),
token BLOB,
authentication BLOB
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `oauth_code`;
create table oauth_code (
code VARCHAR(256), authentication BLOB
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `oauth_client_details`
(`client_id`,
`resource_ids`,
`client_secret`,
`scope`,
`authorized_grant_types`,
`web_server_redirect_uri`,
`authorities`,
`access_token_validity`,
`refresh_token_validity`,
`additional_information`,
`autoapprove`)
VALUES
('my-trusted-client',
'spring-boot-application',
'ICkqckKOQWCdoXwq',
'read,trust',
'password,client_credentials,authorization_code,refresh_token,implicit',
NULL,
'ROLE_CLIENT,ROLE_TRUSTED_CLIENT',
3600,
3600,
NULL,
NULL);
|
USE Concurrency;
DROP TABLE IF EXISTS Concurrency.hlthchk.AgentJobs;
CREATE TABLE Concurrency.hlthchk.AgentJobs
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,JobId UNIQUEIDENTIFIER
,JobName SYSNAME
,JobOwner SYSNAME
,JobCategory SYSNAME
,JobDescription NVARCHAR(1024)
,IsEnabled VARCHAR(3)
,JobCreatedOn DATETIME
,JobLastModifiedOn DATETIME
,OriginatingServerName SYSNAME
,JobStartStepNo INT
,JobStartStepName SYSNAME
,IsScheduled VARCHAR(3)
,JobScheduleID UNIQUEIDENTIFIER
,JobScheduleName SYSNAME
,JobDeletionCrtierion VARCHAR(13));
DROP TABLE IF EXISTS Concurrency.hlthchk.Backups;
CREATE TABLE Concurrency.hlthchk.Backups
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,DatabaseName SYSNAME
,RecoveryModel NVARCHAR(120)
,BackupType VARCHAR(15)
,BackupStartDate DATETIME
,BackupFinishDate DATETIME
,BackupTimeSeconds INT
,DaysSinceBackup INT);
DROP TABLE IF EXISTS Concurrency.hlthchk.BufferPoolSize;
CREATE TABLE Concurrency.hlthchk.BufferPoolSize
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,DatabaseName NVARCHAR(256)
,CachedPagesCount BIGINT
,SizeMb BIGINT);
DROP TABLE IF EXISTS Concurrency.hlthchk.CacheSize;
CREATE TABLE Concurrency.hlthchk.CacheSize
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,ObjectType VARCHAR(28)
,CountPlans INT
,CountUses BIGINT
,AvgUsage BIGINT
,TotalSizeKb INT
,TotalSizeMb INT
,AvgSizeKb INT);
DROP TABLE IF EXISTS Concurrency.hlthchk.DatabaseInfo;
CREATE TABLE Concurrency.hlthchk.DatabaseInfo
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,DatabaseId INT
,DBName SYSNAME
,DBState NVARCHAR(120)
,RecoveryModel NVARCHAR(120)
,DataFileCount INT
,DataFileSize_MB BIGINT
,DataFileFreeSpace_MB BIGINT
,LogFileCount INT
,LogFileSize_MB BIGINT
,LogFileFreeSpace_MB BIGINT
,Log_Larger_Than_Data NVARCHAR(3)
,DBCompatLevel TINYINT
,DBCollation SYSNAME
,Page_Verify_Option_Desc NVARCHAR(120)
,SnapshotIsolation NVARCHAR(120)
,RCSI VARCHAR(3));
DROP TABLE IF EXISTS Concurrency.hlthchk.DbccResults;
CREATE TABLE Concurrency.hlthchk.DbccResults
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,DatabaseName SYSNAME
,LastDBCCCheckDB_RunDate VARCHAR(255));
DROP TABLE IF EXISTS Concurrency.hlthchk.JobHistory;
CREATE TABLE Concurrency.hlthchk.JobHistory
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,ServerName SYSNAME
,JobName SYSNAME
,JobId UNIQUEIDENTIFIER
,RunStatus VARCHAR(30)
,RunDate DATE
,RunTime CHAR(5)
,RunDuration CHAR(8)
,SqlMessageId INT
,SqlSeverity INT
,Message NVARCHAR(MAX));
DROP TABLE IF EXISTS Concurrency.hlthchk.SysConfig
CREATE TABLE Concurrency.hlthchk.SysConfig
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,[Name] NVARCHAR(70)
,ValueInUse SQL_VARIANT
,MatchingValue VARCHAR(10));
DROP TABLE IF EXISTS Concurrency.hlthchk.VlfCounts
CREATE TABLE Concurrency.hlthchk.VlfCounts
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,DBName SYSNAME
,VLFCOUNT INT);
DROP TABLE IF EXISTS Concurrency.hlthchk.VlfCountsByStatus
CREATE TABLE Concurrency.hlthchk.VlfCountsByStatus
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,DBName SYSNAME
,[Status] INT
,VLFCountByStatus INT);
DROP TABLE IF EXISTS Concurrency.hlthchk.Logins
CREATE TABLE Concurrency.hlthchk.Logins
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,RolePrincipalId INT
,RoleName SYSNAME
,MemberPrincipalId INT
,MemberName SYSNAME);
DROP TABLE IF EXISTS Concurrency.hlthchk.OptimizerInfo
CREATE TABLE Concurrency.hlthchk.OptimizerInfo
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,[Counter] NVARCHAR(MAX)
,Occurrence BIGINT
,[Value] FLOAT);
DROP TABLE IF EXISTS Concurrency.hlthchk.PlanCache;
CREATE TABLE Concurrency.hlthchk.PlanCache
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,StatementText NVARCHAR(MAX)
,ExecutionCount BIGINT
,TotalWorkerTimeMs BIGINT
,AvgWorkerTimeMs BIGINT
,TotalLogicalReads BIGINT
,AvgLogicalReads BIGINT
,TotalElapsedTimeMs BIGINT
,AvgElapsedTimeMs BIGINT
,CreationTime DATETIME
,LastExecutionTime DATETIME
,HoursInCache INT
,DatabaseName SYSNAME NULL);
DROP TABLE IF EXISTS Concurrency.hlthchk.IoStats;
CREATE TABLE Concurrency.hlthchk.IoStats
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,DatabaseName SYSNAME
,FileType NVARCHAR(6)
,PhysicalName NVARCHAR(520)
,NumOfReads BIGINT
,MbRead BIGINT
,IoStallReadMs BIGINT
,AvgReadStallMs BIGINT
,NumOfWrites BIGINT
,MbWritten BIGINT
,IoStallWriteMs BIGINT
,AvgWriteStallMs BIGINT);
DROP TABLE IF EXISTS Concurrency.hlthchk.WaitStats;
CREATE TABLE Concurrency.hlthchk.WaitStats
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,WaitType NVARCHAR(120)
,SumWaitingTasksCount BIGINT
,SumWaitTimeMs BIGINT
,SumWaitTimeSec BIGINT
,AvgWaitTimeMs BIGINT
,PercentTotalTime NUMERIC
,SumSignalWaitTimeMs BIGINT);
DROP TABLE IF EXISTS Concurrency.hlthchk.ServerPrincipals;
CREATE TABLE Concurrency.hlthchk.ServerPrincipals
(RowId INT IDENTITY(1,1)
,InsertDate DATETIME DEFAULT CURRENT_TIMESTAMP
,PrincipalName SYSNAME
,[SID] VARBINARY(85)
,TypeDesc NVARCHAR(120)
,IsDisabled BIT
,DefaultDatabaseName SYSNAME);
|
ALTER TABLE `crm_content` RENAME TO `crm_record`;
ALTER TABLE `crm_record` MODIFY COLUMN `json` json DEFAULT NULL COMMENT 'Records in JSON format.';
ALTER TABLE `crm_content_column` RENAME TO `crm_record_column`;
ALTER TABLE `crm_record_column` CHANGE COLUMN `content_id` `record_id` bigint(20);
ALTER TABLE `crm_content_links` RENAME TO `crm_record_links`;
ALTER TABLE `crm_record_links` CHANGE COLUMN `content_id` `record_id` bigint(20) unsigned;
ALTER TABLE `crm_record_links` CHANGE COLUMN `rel_content_id` `rel_record_id` bigint(20) unsigned;
|
CREATE OR REPLACE PACKAGE types
AS TYPE cursorType
IS REF CURSOR;
END;
/
CREATE OR REPLACE FUNCTION list_balance
RETURN types.cursorType
IS
acc_cursor types.cursorType;
BEGIN
OPEN acc_cursor FOR
SELECT *
FROM ACCOUNTA;
RETURN(acc_cursor);
END;
/
|
-- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Hôte : database
-- Généré le : Dim 11 août 2019 à 16:35
-- Version du serveur : 5.7.26
-- Version de PHP : 7.2.19
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 */;
--
-- Base de données : `symfonyweb`
--
CREATE DATABASE IF NOT EXISTS `symfonyweb` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `symfonyweb`;
-- --------------------------------------------------------
--
-- Structure de la table `category`
--
CREATE TABLE `category` (
`id` int(11) NOT NULL,
`title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`description` longtext COLLATE utf8mb4_unicode_ci
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Déchargement des données de la table `category`
--
INSERT INTO `category` (`id`, `title`, `description`) VALUES
(1, 'Sport', 'Sports related videos'),
(3, 'Gaming', 'Follow your favorites streamers here');
-- --------------------------------------------------------
--
-- Structure de la table `migration_versions`
--
CREATE TABLE `migration_versions` (
`version` varchar(14) COLLATE utf8mb4_unicode_ci NOT NULL,
`executed_at` datetime NOT NULL COMMENT '(DC2Type:datetime_immutable)'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Déchargement des données de la table `migration_versions`
--
INSERT INTO `migration_versions` (`version`, `executed_at`) VALUES
('20190728085913', '2019-07-28 08:59:32');
-- --------------------------------------------------------
--
-- Structure de la table `user`
--
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`roles` longtext COLLATE utf8mb4_unicode_ci COMMENT '(DC2Type:simple_array)',
`newsletter` tinyint(1) NOT NULL,
`firstname` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`lastname` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`birthday` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Déchargement des données de la table `user`
--
INSERT INTO `user` (`id`, `email`, `password`, `roles`, `newsletter`, `firstname`, `lastname`, `birthday`) VALUES
(25, 'zaza@zaza.fr', '$2y$13$50FwtSK7WIckfsvov9LQdu/qOqCIdu2BJbVbUIWuvCON.JBLisHjS', 'ROLE_USER,ROLE_ADMIN', 0, NULL, NULL, '1923-04-03 00:00:00'),
(26, 'jean@jean.fr', '$2y$13$qqxZt9HTG0zhdaP7edsrzeLDpPgKM4ZAgGlCzUdT7f7tgaz26EBHW', 'ROLE_USER', 0, 'Jean', 'Juan', '1906-05-05 00:00:00');
-- --------------------------------------------------------
--
-- Structure de la table `video`
--
CREATE TABLE `video` (
`id` int(11) NOT NULL,
`title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`description` longtext COLLATE utf8mb4_unicode_ci,
`created_at` datetime NOT NULL,
`url` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`published` tinyint(1) NOT NULL,
`user_id` int(11) DEFAULT NULL,
`category_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Déchargement des données de la table `video`
--
INSERT INTO `video` (`id`, `title`, `description`, `created_at`, `url`, `published`, `user_id`, `category_id`) VALUES
(29, 'Luka Magic', 'Luka doing Luka\'s Magic', '2019-08-11 18:07:30', 'https://www.youtube.com/watch?v=1YHwhdZncXk', 1, 25, 1),
(30, 'Roller\'s Champions', NULL, '2019-08-11 18:13:13', 'https://www.youtube.com/watch?v=LdM15rkWQGo', 1, 25, 3),
(31, 'Haendel - Sarabande', 'Classical classical music', '2019-08-11 18:16:08', 'https://www.youtube.com/watch?v=klPZIGQcrHA', 0, 25, NULL),
(32, 'Shingeki no Kyojin - Opening 5', 'SUSUME !!!', '2019-08-11 18:17:36', 'https://www.youtube.com/watch?v=NCRcTZiahss', 1, 26, NULL);
--
-- Index pour les tables déchargées
--
--
-- Index pour la table `category`
--
ALTER TABLE `category`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `UNIQ_64C19C12B36786B` (`title`);
--
-- Index pour la table `migration_versions`
--
ALTER TABLE `migration_versions`
ADD PRIMARY KEY (`version`);
--
-- Index pour la table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `UNIQ_8D93D649E7927C74` (`email`);
--
-- Index pour la table `video`
--
ALTER TABLE `video`
ADD PRIMARY KEY (`id`),
ADD KEY `IDX_7CC7DA2CA76ED395` (`user_id`),
ADD KEY `IDX_7CC7DA2C12469DE2` (`category_id`);
--
-- AUTO_INCREMENT pour les tables déchargées
--
--
-- AUTO_INCREMENT pour la table `category`
--
ALTER TABLE `category`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT pour la table `user`
--
ALTER TABLE `user`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=27;
--
-- AUTO_INCREMENT pour la table `video`
--
ALTER TABLE `video`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=33;
--
-- Contraintes pour les tables déchargées
--
--
-- Contraintes pour la table `video`
--
ALTER TABLE `video`
ADD CONSTRAINT `FK_7CC7DA2C12469DE2` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`),
ADD CONSTRAINT `FK_7CC7DA2CA76ED395` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`);
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 */;
|
-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Хост: 127.0.0.1:3306
-- Время создания: Июл 22 2019 г., 01:51
-- Версия сервера: 10.3.13-MariaDB
-- Версия PHP: 5.6.38
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 */;
--
-- База данных: `booker`
--
-- --------------------------------------------------------
--
-- Структура таблицы `b_boardrooms`
--
CREATE TABLE `b_boardrooms` (
`id` int(11) NOT NULL,
`name` varchar(64) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;
--
-- Дамп данных таблицы `b_boardrooms`
--
INSERT INTO `b_boardrooms` (`id`, `name`) VALUES
(1, 'Boardroom 1'),
(2, 'Boardroom 2'),
(3, 'Boardroom 3');
-- --------------------------------------------------------
--
-- Структура таблицы `b_bookings`
--
CREATE TABLE `b_bookings` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`boardroom_id` int(11) NOT NULL,
`description` varchar(255) DEFAULT NULL,
`datetime_start` timestamp NULL DEFAULT NULL,
`datetime_end` timestamp NULL DEFAULT NULL,
`booking_id` int(11) DEFAULT NULL,
`datetime_created` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;
--
-- Дамп данных таблицы `b_bookings`
--
INSERT INTO `b_bookings` (`id`, `user_id`, `boardroom_id`, `description`, `datetime_start`, `datetime_end`, `booking_id`, `datetime_created`) VALUES
(12, 3, 1, 'user2 singe', '2019-07-22 08:15:00', '2019-07-22 09:15:00', NULL, '2019-07-20 17:05:54'),
(18, 2, 1, 'user rec bi-weekly - max', '2019-07-23 10:00:00', '2019-07-23 12:00:00', NULL, '2019-07-20 17:05:54'),
(19, 2, 1, 'user rec bi-weekly - max', '2019-08-06 10:00:00', '2019-08-06 12:00:00', 18, '2019-07-20 17:05:54'),
(20, 2, 1, 'user rec bi-weekly - max', '2019-08-20 10:00:00', '2019-08-20 12:00:00', 18, '2019-07-20 17:05:54'),
(24, 2, 1, 'user rec monthly with holiday', '2019-07-24 06:00:00', '2019-07-24 09:15:00', NULL, '2019-07-20 17:14:17'),
(25, 2, 1, 'user rec monthly with holiday', '2019-08-26 06:00:00', '2019-08-26 09:15:00', 24, '2019-07-20 17:14:17'),
(26, 1, 1, 'admin rec monthly without holiday', '2019-07-26 09:15:00', '2019-07-26 10:15:00', NULL, '2019-07-20 17:14:17'),
(27, 1, 1, 'admin rec monthly without holiday', '2019-08-26 09:15:00', '2019-08-26 10:15:00', 26, '2019-07-20 17:14:17'),
(37, 1, 1, 'single for update checktest', '2019-08-12 08:00:00', '2019-08-12 11:00:00', NULL, '2019-07-20 17:50:29');
-- --------------------------------------------------------
--
-- Структура таблицы `b_roles`
--
CREATE TABLE `b_roles` (
`id` int(11) NOT NULL,
`role` varchar(64) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;
--
-- Дамп данных таблицы `b_roles`
--
INSERT INTO `b_roles` (`id`, `role`) VALUES
(1, 'admin'),
(2, 'user');
-- --------------------------------------------------------
--
-- Структура таблицы `b_users`
--
CREATE TABLE `b_users` (
`id` int(11) NOT NULL,
`name` varchar(128) NOT NULL,
`email` varchar(128) NOT NULL,
`role_id` int(11) NOT NULL,
`login` varchar(128) NOT NULL,
`password` varchar(255) NOT NULL,
`token` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;
--
-- Дамп данных таблицы `b_users`
--
INSERT INTO `b_users` (`id`, `name`, `email`, `role_id`, `login`, `password`, `token`) VALUES
(1, 'admin', 'admin@mail.com', 1, 'admin', '696d29e0940a4957748fe3fc9efd22a3', 'd942af92510591f965b4b320bca6ac0f'),
(2, 'user', 'user@mail.com', 2, 'user', '696d29e0940a4957748fe3fc9efd22a3', NULL),
(3, 'user2', 'user2@mail.com', 2, 'user2', '696d29e0940a4957748fe3fc9efd22a3', '5a7329096633199323ddf4619c8c319a'),
(4, 'admin2', 'admin2@mail.com', 1, 'admin2', '696d29e0940a4957748fe3fc9efd22a3', '95cb1c5ef147ea28331b5109f7a4de6b');
--
-- Индексы сохранённых таблиц
--
--
-- Индексы таблицы `b_boardrooms`
--
ALTER TABLE `b_boardrooms`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `b_bookings`
--
ALTER TABLE `b_bookings`
ADD PRIMARY KEY (`id`),
ADD KEY `user_id` (`user_id`),
ADD KEY `boardroom_id` (`boardroom_id`),
ADD KEY `main_booking_id` (`booking_id`);
--
-- Индексы таблицы `b_roles`
--
ALTER TABLE `b_roles`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `b_users`
--
ALTER TABLE `b_users`
ADD PRIMARY KEY (`id`),
ADD KEY `role_id` (`role_id`);
--
-- AUTO_INCREMENT для сохранённых таблиц
--
--
-- AUTO_INCREMENT для таблицы `b_boardrooms`
--
ALTER TABLE `b_boardrooms`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT для таблицы `b_bookings`
--
ALTER TABLE `b_bookings`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=66;
--
-- AUTO_INCREMENT для таблицы `b_roles`
--
ALTER TABLE `b_roles`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT для таблицы `b_users`
--
ALTER TABLE `b_users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- Ограничения внешнего ключа сохраненных таблиц
--
--
-- Ограничения внешнего ключа таблицы `b_bookings`
--
ALTER TABLE `b_bookings`
ADD CONSTRAINT `b_bookings_ibfk_1` FOREIGN KEY (`boardroom_id`) REFERENCES `b_boardrooms` (`id`),
ADD CONSTRAINT `b_bookings_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `b_users` (`id`);
--
-- Ограничения внешнего ключа таблицы `b_users`
--
ALTER TABLE `b_users`
ADD CONSTRAINT `b_users_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `b_roles` (`id`);
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 */;
|
IF OBJECT_ID(N'tempdb..#TypePayments', N'U') IS NOT NULL
DROP TABLE #TypePayments
CREATE TABLE #TypePayments
(
[Лицевой счет] BIGINT,
Сумма FLOAT
);
INSERT INTO #TypePayments
SELECT
LC,
SUM
FROM OPENROWSET(
'Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;HDR=YES;Database=g:\Bulk\20210813AP1.xlsx',
'select * from [20210813AP1$]')
WITH Оплаты AS (
SELECT LS.Номер,V.ROW_ID As Выписка, D.ROW_ID AS Пачка,SO.ROW_ID, SO.Сумма, SO.Дата
FROM [stack].[Документ] AS V
JOIN [stack].[Документ] AS D ON D.[Платеж-Выписка] = V.row_id
JOIN [stack].[Список оплаты] AS SO ON SO.[Платеж-Список] = D.row_id
JOIN stack.[Лицевые счета] AS LS ON LS.ROW_ID=SO.[Счет-Оплата]
WHERE V.row_id = 2968142
GROUP By LS.Номер,V.ROW_ID , D.ROW_ID ,SO.ROW_ID, SO.Сумма, SO.Дата
)
SELECT *
FROM Оплаты AS O
JOIN #TypePayments AS P ON P.[Дата платежа]=O.Дата AND P.[Лицевой счет клиента]=O.Номер AND P.Сумма=O.Сумма
WITH Оплаты AS (
SELECT LS.Номер, SO.Сумма, SO.Дата
FROM [stack].[Документ] AS V
JOIN [stack].[Документ] AS D ON D.[Платеж-Выписка] = V.row_id
JOIN [stack].[Список оплаты] AS SO ON SO.[Платеж-Список] = D.row_id
JOIN stack.[Лицевые счета] AS LS ON LS.ROW_ID=SO.[Счет-Оплата]
LEFT JOIN [stack].[Показания счетчиков] AS PS ON PS.[Платеж-Счетчики] = SO.row_id
--WHERE V.row_id = 2968142
)
SELECT *
FROM Оплаты AS O
JOIN #TypePayments AS P ON P.[Дата платежа]=O.Дата AND P.[Лицевой счет клиента]=O.Номер AND P.Сумма=O.Сумма
SELECT *
FROM stack.Документ
WHERE ROW_ID=2968142
SELECT *
FROM #TypePayments
|
-- init groups
INSERT INTO groups(id, color, icon, name) VALUES (1, NULL, NULL, 'Admin');
INSERT INTO groups(id, color, icon, name) VALUES (2, NULL, NULL, 'Mod');
INSERT INTO groups(id, color, icon, name) VALUES (3, NULL, NULL, 'User');
select nextval('group_sequence');
select nextval('group_sequence');
select nextval('group_sequence');
-- init categories
INSERT INTO categories(id, description, name, position, slug, parent_id) VALUES
(0, 'Home', 'home', 0, 'home', NULL);
-- init admin permissions
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'topic.create');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'topic.edit.own.title');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'topic.edit.own.category');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'topic.locked.own');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'topic.delete.own');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'post.create');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'post.edit.own.content');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'post.delete.own');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'user.lock');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'ip.read');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'report.manage');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'topic.edit.title');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'topic.edit.category');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'topic.locked');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'topic.delete');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'topic.pinned');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'topic.feature');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'post.edit.content');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'post.delete');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'admin');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'group.all');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'category.all');
INSERT INTO group_permissions(group_id, permissions) VALUES (1, 'setting.all');
-- init mod permissions
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'topic.create');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'topic.edit.own.title');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'topic.edit.own.category');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'topic.locked.own');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'topic.delete.own');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'post.create');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'post.edit.own.content');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'post.delete.own');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'user.lock');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'ip.read');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'report.manage');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'topic.edit.title');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'topic.edit.category');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'topic.locked');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'topic.delete');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'topic.pinned');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'topic.feature');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'post.edit.content');
INSERT INTO group_permissions(group_id, permissions) VALUES (2, 'post.delete');
-- init user permissions
INSERT INTO group_permissions(group_id, permissions) VALUES (3, 'topic.create');
INSERT INTO group_permissions(group_id, permissions) VALUES (3, 'topic.edit.own.title');
INSERT INTO group_permissions(group_id, permissions) VALUES (3, 'topic.edit.own.category');
INSERT INTO group_permissions(group_id, permissions) VALUES (3, 'topic.locked.own');
INSERT INTO group_permissions(group_id, permissions) VALUES (3, 'topic.delete.own');
INSERT INTO group_permissions(group_id, permissions) VALUES (3, 'post.create');
INSERT INTO group_permissions(group_id, permissions) VALUES (3, 'post.edit.own.content');
INSERT INTO group_permissions(group_id, permissions) VALUES (3, 'post.delete.own');
-- init secret
INSERT INTO secrets(key, value) VALUES ('userLinkFormat', '<a class="user-link" href="/user/%s">@%s </a>');
INSERT INTO secrets(key, value) VALUES ('url', 'http://localhost');
INSERT INTO secrets(key, value) VALUES ('mail.host', 'smtp.mailgun.org');
INSERT INTO secrets(key, value) VALUES ('mail.username', 'username');
INSERT INTO secrets(key, value) VALUES ('mail.password', 'password');
INSERT INTO secrets(key, value) VALUES ('mail.address', 'noreply@bicarb.org');
INSERT INTO secrets(key, value) VALUES ('mail.personal', 'Bicarb');
-- init setting
INSERT INTO settings(key, value) VALUES ('Content-Security-Policy', 'default-src ''self''; base-uri ''self''; script-src ''self'' ''nonce-%s'' https:; style-src ''self'' ''unsafe-inline'' https:; img-src ''self'' https: data:; font-src ''self'' https: data:; connect-src ''self'' ws://localhost; frame-src ''self'' https://www.youtube.com');
|
SELECT part.id AS id,
tenant.id AS tenant_id,
part.name AS name,
part.number AS number,
part.universal AS is_universal,
part.unit AS unit,
part.warehouse_id AS warehouse_id,
COALESCE(stock.quantity, 0) AS quantity,
COALESCE(ordered.quantity, 0) AS ordered,
COALESCE(reserved.quantity, 0) AS reserved,
COALESCE(crosses.parts, '[]'::JSON) AS analogs,
COALESCE(notes.json, '[]'::JSON) AS notes,
m.name AS manufacturer_name,
m.id AS manufacturer_id,
m.localized_name AS manufacturer_localized_name,
pc.cases AS cases,
UPPER(CONCAT_WS(' ', part.name, m.name, m.localized_name, pc.cases)) AS search,
COALESCE(price.price_amount, 0) AS price,
COALESCE(discount.discount_amount, 0) AS discount,
COALESCE(income.price_amount, 0) AS income,
COALESCE(part_required.order_from_quantity, 0) AS order_from_quantity,
COALESCE(part_required.order_up_to_quantity, 0) AS order_up_to_quantity,
COALESCE(supply.json, '[]'::JSON) AS supplies,
COALESCE(supply.quantity, 0) AS supplies_quantity
FROM part
JOIN tenant ON TRUE
JOIN manufacturer m ON part.manufacturer_id = m.id
LEFT JOIN (SELECT part_case.part_id, ARRAY_TO_STRING(ARRAY_AGG(vm.case_name), ' ') AS cases
FROM part_case
LEFT JOIN vehicle_model vm ON vm.id = part_case.vehicle_id
GROUP BY part_case.part_id) pc ON pc.part_id = part.id
LEFT JOIN (SELECT ROW_NUMBER() OVER (PARTITION BY pra.part_id, pra.tenant_id ORDER BY pra.id DESC) AS rownum,
pra.*
FROM part_required_availability pra) part_required
ON part_required.part_id = part.id AND part_required.rownum = 1 AND tenant.id = part_required.tenant_id
LEFT JOIN (SELECT ROW_NUMBER() OVER (PARTITION BY pp.part_id, pp.tenant_id ORDER BY pp.id DESC) AS rownum,
pp.*
FROM part_price pp) price ON price.part_id = part.id AND price.rownum = 1 AND tenant.id = price.tenant_id
LEFT JOIN (SELECT ROW_NUMBER() OVER (PARTITION BY pd.part_id, pd.tenant_id ORDER BY pd.id DESC) AS rownum,
pd.*
FROM part_discount pd) discount ON discount.part_id = part.id AND discount.rownum = 1 AND tenant.id = discount.tenant_id
LEFT JOIN (SELECT ROW_NUMBER() OVER (PARTITION BY income_part.part_id, income_part.tenant_id ORDER BY income_part.id DESC) AS rownum,
income_part.*
FROM income_part) income ON income.part_id = part.id AND income.rownum = 1
LEFT JOIN (SELECT motion.part_id, motion.tenant_id, SUM(motion.quantity) AS quantity FROM motion GROUP BY motion.part_id, motion.tenant_id) stock
ON stock.part_id = part.id AND tenant.id = stock.tenant_id
LEFT JOIN (SELECT order_item_part.part_id, order_item.tenant_id, SUM(order_item_part.quantity) AS quantity
FROM order_item_part
JOIN order_item ON order_item.id = order_item_part.id
LEFT JOIN order_close ON order_item.order_id = order_close.order_id
WHERE order_close IS NULL
GROUP BY order_item_part.part_id, order_item.tenant_id) AS ordered
ON ordered.part_id = part.id AND tenant.id = ordered.tenant_id
LEFT JOIN (SELECT order_item_part.part_id, reservation.tenant_id, SUM(reservation.quantity) AS quantity
FROM reservation
JOIN order_item_part ON order_item_part.id = reservation.order_item_part_id
GROUP BY order_item_part.part_id, reservation.tenant_id) AS reserved
ON reserved.part_id = part.id AND tenant.id = reserved.tenant_id
LEFT JOIN (SELECT JSON_AGG(
JSON_BUILD_OBJECT(
'supplier_id', sub.supplier_id,
'quantity', sub.quantity,
'updatedAt', sub.updated_at
)
) AS json,
sub.tenant_id,
sub.part_id,
SUM(sub.quantity) AS quantity
FROM (SELECT part_supply.part_id,
part_supply.tenant_id,
part_supply.supplier_id,
SUM(part_supply.quantity) AS quantity,
MAX(created_by.created_at) AS updated_at
FROM part_supply
LEFT JOIN created_by ON created_by.id = part_supply.id
GROUP BY part_supply.part_id, part_supply.tenant_id, part_supply.supplier_id
HAVING SUM(part_supply.quantity) <> 0
) sub
GROUP BY sub.part_id, sub.tenant_id) supply
ON supply.part_id = part.id AND tenant.id = supply.tenant_id
LEFT JOIN (SELECT pcp.part_id, JSON_AGG(pcp2.part_id) FILTER ( WHERE pcp2.part_id IS NOT NULL ) AS parts
FROM part_cross_part pcp
LEFT JOIN part_cross_part pcp2
ON pcp2.part_cross_id = pcp.part_cross_id AND pcp2.part_id <> pcp.part_id
GROUP BY pcp.part_id) crosses ON crosses.part_id = part.id
LEFT JOIN (SELECT note.subject,
note.tenant_id,
JSON_AGG(
JSON_BUILD_OBJECT(
'type', note.type,
'text', note.text
)
) AS json
FROM note
GROUP BY note.subject, note.tenant_id) notes ON notes.subject = part.id AND tenant.id = notes.tenant_id
|
SELECT store_name 'Наименование магазина', product_name 'Наименование товара',
quantity 'Количество на остатке', unit_name 'Ед. изм.'
FROM stores
INNER JOIN stocks ON stores.store_id = stocks.store_id
INNER JOIN products ON stocks.product_id = products.product_id
INNER JOIN units ON products.unit_id = units.unit_id
|
-- get-schema-size.sql
-- Jared Still
-- estimate of size for export
-- indexes are excluded
-- most system accounts excluded
-- use the 'oracle_maintained' column if available
-- the hard coded list is here so it would work on 10g
set linesize 200 trimspool on
set tab off
set pagesize 100
col owner format a30
col segment_name format a30
col segment_type format a30
col size_m format 99,999,999
clear break
break on owner skip 1 on segment_type on report
compute sum of size_m on owner
compute sum of size_m on segment_type
compute sum of size_m on report
select distinct
owner
, segment_type
--, segment_name
, sum(( s.blocks * ts.block_size) / power(2,20)) over (partition by owner, segment_type) size_m
from dba_segments s
join dba_tablespaces ts on ts.tablespace_name = s.tablespace_name
where
segment_type not like 'INDEX%'
and segment_type not in (
'CLUSTER'
,'ROLLBACK'
,'SYSTEM STATISTICS'
,'TYPE2 UNDO'
)
and owner not in (
'ANONYMOUS'
,'APPQOSSYS'
,'AUDSYS'
,'CTXSYS'
,'DBSFWUSER'
,'DBSNMP'
,'DIP'
,'DVF'
,'DVSYS'
,'GGSYS'
,'GSMADMIN_INTERNAL'
,'GSMCATUSER'
,'GSMROOTUSER'
,'GSMUSER'
,'LBACSYS'
,'MDDATA'
,'MDSYS'
,'OJVMSYS'
,'OLAPSYS'
,'ORACLE_OCM'
,'ORDDATA'
,'ORDPLUGINS'
,'ORDSYS'
,'OUTLN'
,'REMOTE_SCHEDULER_AGENT'
,'SI_INFORMTN_SCHEMA'
,'SYS$UMF'
,'SYS'
,'SYSBACKUP'
,'SYSDG'
,'SYSKM'
,'SYSRAC'
,'SYSTEM'
,'WMSYS'
,'XDB'
,'XS$NULL'
)
order by
owner
, segment_type
--, segment_name
/
|
ALTER TABLE listings ADD COLUMN user_id INT;
ALTER TABLE listings ADD FOREIGN KEY (user_id) REFERENCES users(id);
|
USE `tree`;
/*
-- Query:
-- Date: 2017-07-18 14:01
*/
INSERT INTO `tree` (`tree_id`,`treeSlug`,`tree_content`,`tree_title`,`tree_owner`,`tree_created_by`,`tree_updated_by`) VALUES (1,'citizen','','Are You Eligible to be a US Citizen',1,1,1);
/*
-- Query:
-- Date: 2017-07-18 14:02
*/
INSERT INTO `tree_element_type` (`el_type_id`,`el_type`) VALUES (1,'column');
INSERT INTO `tree_element_type` (`el_type_id`,`el_type`) VALUES (2,'question');
INSERT INTO `tree_element_type` (`el_type_id`,`el_type`) VALUES (3,'option');
INSERT INTO `tree_element_type` (`el_type_id`,`el_type`) VALUES (4,'end');
/*
-- Query:
-- Date: 2017-07-18 14:00
*/
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_content`,`el_created_by`,`el_updated_by`) VALUES (1,1,1,'Main Column','',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_content`,`el_created_by`,`el_updated_by`) VALUES (2,1,2,'Are you at least 18 years old?','',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_content`,`el_created_by`,`el_updated_by`) VALUES (3,1,3,'Yes','',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_content`,`el_created_by`,`el_updated_by`) VALUES (4,1,3,'No','',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_content`,`el_created_by`,`el_updated_by`) VALUES (5,1,4,'You are elegible.','You can apply for US Citizenship if you want to.',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_content`,`el_created_by`,`el_updated_by`) VALUES (6,1,4,'You are not eligible.','You will get rejected from US Citizenship if you apply right now.',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_content`,`el_created_by`,`el_updated_by`) VALUES (7,1,3,'Start Over','Want to go through this decision tree again?',1,1);
/*
-- Query:
-- Date: 2017-07-18 14:01
*/
INSERT INTO `tree_element_order` (`el_order_id`,`el_id`,`el_order`) VALUES (1,3,1);
INSERT INTO `tree_element_order` (`el_order_id`,`el_id`,`el_order`) VALUES (2,4,0);
INSERT INTO `tree_element_order` (`el_order_id`,`el_id`,`el_order`) VALUES (3,7,0);
INSERT INTO `tree_element_order` (`el_order_id`,`el_id`,`el_order`) VALUES (4,1,0);
INSERT INTO `tree_element_order` (`el_order_id`,`el_id`,`el_order`) VALUES (5,2,0);
/*
-- Query:
-- Date: 2017-07-18 14:01
*/
INSERT INTO `tree_element_container` (`el_container_id`,`el_id`,`el_id_child`) VALUES (1,1,2);
INSERT INTO `tree_element_container` (`el_container_id`,`el_id`,`el_id_child`) VALUES (2,2,3);
INSERT INTO `tree_element_container` (`el_container_id`,`el_id`,`el_id_child`) VALUES (3,2,4);
INSERT INTO `tree_element_destination` (`el_destination_id`,`el_id`,`el_id_destination`) VALUES (1,3,5);
INSERT INTO `tree_element_destination` (`el_destination_id`,`el_id`,`el_id_destination`) VALUES (2,4,6);
INSERT INTO `tree_element_destination` (`el_destination_id`,`el_id`,`el_id_destination`) VALUES (3,7,2);
INSERT INTO `tree`.`tree_element` (`el_id`, `tree_id`, `el_type_id`, `el_title`, `el_created_by`, `el_updated_by`) VALUES ('8', '1', '2', 'Are you a permanent resident of the US?', '1', '1');
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (8,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (9,1,3,'Yes',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (10,1,3,'No',1,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (9,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (10,0);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (10,6);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (9,11);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (8,9);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (8,10);
INSERT INTO `tree`.`tree_element` (`el_id`, `tree_id`, `el_type_id`, `el_title`, `el_created_by`, `el_updated_by`) VALUES ('11', '1', '2', 'Have you been issued a Permanent Resident Card?', '1', '1');
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (11,2);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (12,1,3,'Yes',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (13,1,3,'No',1,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (12,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (13,0);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (13,6);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (12,14);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (11,12);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (11,13);
INSERT INTO `tree`.`tree_element` (`el_id`, `tree_id`, `el_type_id`, `el_title`, `el_created_by`, `el_updated_by`) VALUES ('14', '1', '2', 'I have been a permanent resident for...', '1', '1');
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (14,3);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (15,1,3,'Less than three years',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (16,1,3,'Three or more years',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (17,1,3,'Five or more years',1,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (15,0);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (16,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (17,2);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (15,6);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (16,18);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (17,1);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (14,15);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (14,16);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (14,17);
INSERT INTO `tree`.`tree_element` (`el_id`, `tree_id`, `el_type_id`, `el_title`, `el_created_by`, `el_updated_by`) VALUES ('18', '1', '2', 'I am married to and living with a US Citizen.', '1', '1');
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (18,4);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (1,18);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (19,1,3,'Yes',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (20,1,3,'No',1,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (19,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (20,0);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (20,6);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (19,21);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (18,19);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (18,20);
INSERT INTO `tree`.`tree_element` (`el_id`, `tree_id`, `el_type_id`, `el_title`, `el_created_by`, `el_updated_by`) VALUES ('21', '1', '2', 'I have been married to that US Citizen for at least the past three years.', '1', '1');
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (21,5);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (1,21);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (22,1,3,'Yes',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (23,1,3,'No',1,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (22,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (23,0);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (23,6);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (22,23);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (21,22);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (21,21);
INSERT INTO `tree`.`tree_element` (`el_id`, `tree_id`, `el_type_id`, `el_title`, `el_created_by`, `el_updated_by`) VALUES ('26', '1', '2', 'During the past three years, I have not been out of the country for 18 months or more.', '1', '1');
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (26,7);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (1,26);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (27,1,3,'Yes',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (28,1,3,'No',1,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (27,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (28,0);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (28,6);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (27,29);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (26,27);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (26,28);
INSERT INTO `tree`.`tree_element` (`el_id`, `tree_id`, `el_type_id`, `el_title`, `el_created_by`, `el_updated_by`) VALUES ('29', '1', '2', 'During the last five years, I have not been out of the US for 30 months or more.', '1', '1');
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (29,8);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (30,1,3,'Yes',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (31,1,3,'No',1,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (30,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (31,0);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (31,6);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (30,5);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (29,30);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (29,31);
INSERT INTO `tree`.`tree_element` (`el_id`, `tree_id`, `el_type_id`, `el_title`, `el_created_by`, `el_updated_by`) VALUES ('33', '1', '2', 'My spouse has been a US Citizen for at least the past three years.', '1', '1');
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (33,6);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (1,33);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (34,1,3,'Yes',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (35,1,3,'No',1,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (34,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (35,0);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (35,6);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (34,26);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (33,34);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (33,35);
INSERT INTO `tree`.`tree_element` (`el_id`, `tree_id`, `el_type_id`, `el_title`, `el_created_by`, `el_updated_by`) VALUES ('40', '1', '2', 'During the last three to five years, I have not taken a trip out of the United States that lasted one year or more.', '1', '1');
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (40,7);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (41,1,3,'Yes',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (42,1,3,'No',1,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (41,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (42,0);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (42,6);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (41,43);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (40,41);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (40,42);
INSERT INTO `tree`.`tree_element` (`el_id`, `tree_id`, `el_type_id`, `el_title`, `el_created_by`, `el_updated_by`) VALUES ('43', '1', '2', 'I have resided in the district or state in which I am applying for citizenship for the last three months.', '1', '1');
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (43,8);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (44,1,3,'Yes',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (45,1,3,'No',1,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (44,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (45,0);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (45,6);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (44,46);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (43,44);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (43,45);
INSERT INTO `tree`.`tree_element` (`el_id`, `tree_id`, `el_type_id`, `el_title`, `el_created_by`, `el_updated_by`) VALUES ('46', '1', '2', 'I can read, write and speak basic English.', '1', '1');
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (46,8);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (47,1,3,'Yes',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (48,1,3,'No',1,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (47,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (48,0);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (48,6);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (47,49);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (46,47);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (46,48);
INSERT INTO `tree`.`tree_element` (`el_id`, `tree_id`, `el_type_id`, `el_title`, `el_created_by`, `el_updated_by`) VALUES ('52', '1', '2', 'I know the fundamentals of U.S. history and the form and principles of the U.S. government.', '1', '1');
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (52,8);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (53,1,3,'Yes',1,1);
INSERT INTO `tree_element` (`el_id`,`tree_id`,`el_type_id`,`el_title`,`el_created_by`,`el_updated_by`) VALUES (54,1,3,'No',1,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (53,1);
INSERT INTO `tree_element_order` (`el_id`,`el_order`) VALUES (54,0);
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (54,6);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (52,53);
INSERT INTO `tree_element_container` (`el_id`,`el_id_child`) VALUES (52,54);
/* Destination from Previous's Yes to This Question. */
INSERT INTO `tree_element_destination` (`el_id`,`el_id_destination`) VALUES (50,52);
|
REM ------------------------------------------------------------------------
REM REQUIREMENTS:
REM SELECT on V$
REM ------------------------------------------------------------------------
REM PURPOSE:
REM Show jobs details
REM ------------------------------------------------------------------------
set linesize 96
set pages 100
set feedback off
set verify off
col job for 99999 head Job
col log_user for a&2 head "User Name"
col last_date head "Last Date"
col failures for 999 head Fail
col what for a30 head What
SELECT job, log_user, last_date, failures, what
FROM dba_jobs
WHERE log_user &1
;
prompt
exit
|
[MYSQL]
entityNum = 1
|
Drop schema leo;
CREATE schema leo; |
alter table Cemetery drop constraint FKCE89E51279E16DEC
alter table Grave drop constraint FK41DD1E5B0ABD199
alter table Grave drop constraint FK41DD1E5AA7CB23A
alter table Person drop constraint FK8E48877570B4C7A4
alter table Person drop constraint FK8E488775ABCEE677
alter table Person drop constraint FK8E488775EF7942C
alter table Person drop constraint FK8E48877570F3F3DA
alter table Person drop constraint FK8E4887757DF6B27A
alter table Person drop constraint FK8E4887758A840FFA
alter table Person drop constraint FK8E48877580E8A6BA
alter table Person drop constraint FK8E4887759894923A
alter table Person drop constraint FK8E488775918DBD79
alter table Person_CauseOfDeath drop constraint FK485AEADE4FAFE35A
alter table Person_CauseOfDeath drop constraint FK485AEADE7808DA3B
alter table Person_Grave drop constraint FKF4FA909B7A4E4C31
alter table Person_Grave drop constraint FKF4FA909B4FAFE35A
drop table Camp
drop table Category
drop table CauseOfDeath
drop table Cemetery
drop table FlexibleDate
drop table Grave
drop table InfoPage
drop table KgUser
drop table Nationality
drop table Person
drop table PersonDetails
drop table Person_CauseOfDeath
drop table Person_Grave
drop table PostalDistrict
drop table Rank
drop table Stalag
drop sequence hibernate_sequence
create table Camp (id int8 not null, description text, latitude float8, longitude float8, name varchar(255) not null unique, primary key (id))
create table Category (id int8 not null, description text, name varchar(255) not null unique, primary key (id))
create table CauseOfDeath (id int8 not null, causeGroup varchar(255), description varchar(255), name varchar(255) not null unique, primary key (id))
create table Cemetery (id int8 not null, address varchar(255), latitude float8, longitude float8, name varchar(255) not null unique, postalDistrict_postcode int4, primary key (id))
create table FlexibleDate (id int8 not null, approximate bool not null, day int4, month int4, year int4, primary key (id))
create table Grave (id int8 not null, graveField varchar(255), graveNumber varchar(255), graveRow varchar(255), latitude float8, longitude float8, massGrave bool not null, moved bool not null, reference text, cemetery_id int8, dateOfBurial_id int8, primary key (id))
create table InfoPage (id int8 not null, html text, language varchar(255), pageName varchar(255) not null, primary key (id))
create table KgUser (id int8 not null, credentialsNonExpired bool not null, enabled bool not null, name varchar(255), password varchar(255), role varchar(255), username varchar(255) unique, primary key (id))
create table Nationality (id int8 not null, name varchar(255) unique, primary key (id))
create table Person (id int8 not null, causeOfDeathDescription varchar(255), createdDate timestamp default current_timestamp not null, obdNumber int8, placeOfDeath varchar(255), prisonerNumber int4, remarks text, camp_id int8, category_id int8, cyrillicDetails_id int8, dateOfBirth_id int8, dateOfDeath_id int8, nationality_id int8, rank_id int8, stalag_id int8, westernDetails_id int8, primary key (id))
create table PersonDetails (id int8 not null, firstName varchar(255), lastName varchar(255), nameOfFather varchar(255), placeOfBirth varchar(255), primary key (id))
create table Person_CauseOfDeath (Person_id int8 not null, causesOfDeath_id int8 not null, primary key (Person_id, causesOfDeath_id))
create table Person_Grave (Person_id int8 not null, graves_id int8 not null, unique (graves_id))
create table PostalDistrict (postcode int4 not null unique, countyId int4 not null, name varchar(255) not null, primary key (postcode))
create table Rank (id int8 not null, name varchar(255) unique, primary key (id))
create table Stalag (id int8 not null, description text, latitude float8, longitude float8, name varchar(255) not null unique, primary key (id))
alter table Cemetery add constraint FKCE89E51279E16DEC foreign key (postalDistrict_postcode) references PostalDistrict
alter table Grave add constraint FK41DD1E5B0ABD199 foreign key (dateOfBurial_id) references FlexibleDate
alter table Grave add constraint FK41DD1E5AA7CB23A foreign key (cemetery_id) references Cemetery
alter table Person add constraint FK8E48877570B4C7A4 foreign key (dateOfDeath_id) references FlexibleDate
alter table Person add constraint FK8E488775ABCEE677 foreign key (westernDetails_id) references PersonDetails
alter table Person add constraint FK8E488775EF7942C foreign key (cyrillicDetails_id) references PersonDetails
alter table Person add constraint FK8E48877570F3F3DA foreign key (camp_id) references Camp
alter table Person add constraint FK8E4887757DF6B27A foreign key (nationality_id) references Nationality
alter table Person add constraint FK8E4887758A840FFA foreign key (rank_id) references Rank
alter table Person add constraint FK8E48877580E8A6BA foreign key (category_id) references Category
alter table Person add constraint FK8E4887759894923A foreign key (stalag_id) references Stalag
alter table Person add constraint FK8E488775918DBD79 foreign key (dateOfBirth_id) references FlexibleDate
alter table Person_CauseOfDeath add constraint FK485AEADE4FAFE35A foreign key (Person_id) references Person
alter table Person_CauseOfDeath add constraint FK485AEADE7808DA3B foreign key (causesOfDeath_id) references CauseOfDeath
alter table Person_Grave add constraint FKF4FA909B7A4E4C31 foreign key (graves_id) references Grave
alter table Person_Grave add constraint FKF4FA909B4FAFE35A foreign key (Person_id) references Person
create sequence hibernate_sequence
|
/*Ejercicio 10 (multiples instrucciones)
LeoMetro quiere premiar mensualmente a los pasajeros que más utilizan el transporte público. Para ello necesitamos una función que nos devuelva una tabla con los que deben ser premiados.
Los premios tienen tres categorías: 1: Mayores de 65 años, 2: menores de 25 años y 3: resto. En cada categoría se premia a tres personas. Los elegidos serán los que hayan realizado más viajes en ese mes. En caso de empatar en número de viajes, se dará prioridad al que más dinero se haya gastado.
Queremos una función que reciba como parámetros un mes (TinyInt) y un año (SmallInt) y nos devuelva una tabla con los premiados de ese mes. Las columnas de la tabla serán: ID del pasajero, nombre, apellidos, número de viajes realizados en el mes, total de dinero gastado, categoría y posición (primero, segundo o tercero) en su categoría.
La tabla tendrá
*/
CREATE FUNCTION FPrueba() RETURNS @Prueba TABLE(
Id smallint NOT NULL
) AS
BEGIN
RETURN
END |
[getResult]
SELECT
org.code,
p.itemno,
job.name,
grade.grade,
currentstep.step,
currentinc.amount * 12 AS currentannual,
pds.person_lastname,
pds.person_firstname,
pds.person_middlename,
pds.person_gender,
pds.person_birthdate,
pds.tin,
sr.datefrom,
sr1.datefrom AS lastprodate,
empstat.code AS empstatcode,
csctbl.name AS cscname
FROM references_tblorganizationunit org
INNER JOIN hrmis_tblemploymentplantilla p ON p.`org_orgunitid` = org.orgunitid
INNER JOIN references_tbljobposition job ON job.objid = p.jobposition_objid
LEFT JOIN hrmis_appointmentpermanent ap ON ap.plantilla_objid = p.objid
INNER JOIN references_tblpaygradeandstepincrement grade ON grade.`objid` = job.`paygrade_objid`
LEFT JOIN references_tblpaygradeandstepincrement currentstep ON currentstep.`grade` = grade.`grade` AND currentstep.`step` = IF((TIMESTAMPDIFF(YEAR,ap.effectivefrom,NOW())/3) < 1 ,1,FLOOR((TIMESTAMPDIFF(YEAR,ap.effectivefrom,NOW())/3)+1))
LEFT JOIN hrmis_tblpayrollsalaryscheduleitem currentinc ON currentinc.paygradeandstepincrementid = currentstep.`objid` AND currentinc.salarytrancheid = (SELECT objid FROM hrmis_tblpayrollsalarytranche WHERE NOW() BETWEEN effectivefromdate AND effectivetodate)
LEFT JOIN hrmis_pds pds ON pds.`objid` = ap.`pds_objid`
LEFT JOIN hrmis_servicerecords sr ON sr.personnelaction_name LIKE 'ORIGINAL' AND sr.employmentstatus_objid = (SELECT objid FROM `references_tblemptemploymentstatus` es WHERE es.`name` = 'PERMANENT') AND sr.pdsid = ap.`pds_objid`
LEFT JOIN hrmis_servicerecords sr1 ON sr1.pdsid = ap.`pds_objid` AND sr1.datefrom = (SELECT MAX(datefrom) FROM hrmis_servicerecords WHERE pdsid = ap.`pds_objid` AND dateto > datefrom)
LEFT JOIN references_tblemptemploymentstatus empstat ON empstat.objid = ap.status_objid AND empstat.name = 'PERMANENT'
LEFT JOIN hrmis_pds_civilservice csc ON csc.pdsid = ap.`pds_objid`
LEFT JOIN references_tbleligibility csctbl ON csctbl.objid = csc.eligibility_objid
WHERE p.type = 'Permanent' AND orgunitid = '${funnel}' ORDER BY p.itemno ASC;
[getCasualResult]
SELECT
org.code,
p.itemno,
job.name,
grade.grade,
currentstep.step,
currentinc.amount * 12 AS currentannual,
pds.person_lastname,
pds.person_firstname,
pds.person_middlename,
pds.person_gender,
pds.person_birthdate,
pds.tin,
sr.datefrom,
sr1.datefrom AS lastprodate,
empstat.code AS empstatcode,
csctbl.name AS cscname
FROM references_tblorganizationunit org
INNER JOIN hrmis_tblemploymentplantilla p ON p.`org_orgunitid` = org.orgunitid
INNER JOIN references_tbljobposition job ON job.objid = p.jobposition_objid
LEFT JOIN hrmis_appointmentcasual apc ON apc.org_orgunitid = p.`org_orgunitid` AND apc.effectiveuntil = (SELECT MAX(effectiveuntil) FROM hrmis_appointmentcasual WHERE org_orgunitid = p.`org_orgunitid` AND effectiveuntil > effectivefrom)
LEFT JOIN hrmis_appointmentcasualitems api ON api.parentid = apc.objid AND api.plantilla_objid = p.objid
INNER JOIN references_tblpaygradeandstepincrement grade ON grade.`objid` = job.`paygrade_objid`
LEFT JOIN references_tblpaygradeandstepincrement currentstep ON currentstep.`grade` = grade.`grade` AND currentstep.`step` = IF((TIMESTAMPDIFF(YEAR,apc.effectivefrom,NOW())/3) < 1 ,1,FLOOR((TIMESTAMPDIFF(YEAR,apc.effectivefrom,NOW())/3)+1))
LEFT JOIN hrmis_tblpayrollsalaryscheduleitem currentinc ON currentinc.paygradeandstepincrementid = currentstep.`objid` AND currentinc.salarytrancheid = (SELECT objid FROM hrmis_tblpayrollsalarytranche WHERE NOW() BETWEEN effectivefromdate AND effectivetodate)
LEFT JOIN hrmis_pds pds ON pds.`objid` = api.`pds_objid`
LEFT JOIN hrmis_servicerecords sr ON sr.personnelaction_name LIKE 'ORIGINAL' AND sr.employmentstatus_objid = (SELECT objid FROM `references_tblemptemploymentstatus` es WHERE es.`name` = 'Casual') AND sr.pdsid = api.`pds_objid`
LEFT JOIN hrmis_servicerecords sr1 ON sr1.pdsid = api.`pds_objid` AND sr1.datefrom = (SELECT MAX(datefrom) FROM hrmis_servicerecords WHERE pdsid = api.`pds_objid` AND dateto > datefrom)
LEFT JOIN references_tblemptemploymentstatus empstat ON empstat.name = apc.status AND empstat.name = 'Casual'
LEFT JOIN hrmis_pds_civilservice csc ON csc.pdsid = api.`pds_objid`
LEFT JOIN references_tbleligibility csctbl ON csctbl.objid = csc.eligibility_objid
WHERE p.type = 'Casual' AND orgunitid = '${funnel}' ORDER BY p.itemno ASC;
|
CREATE DATABASE IF NOT EXISTS database automocion;
CREATE TABLE usuarios (
id INT PRIMARY KEY AUTO_INCREMENT,
usuario VARCHAR(20),
nombre VARCHAR(20),
sexo VARCHAR(1),
nivel TINYINT,
email VARCHAR(50),
telefono VARCHAR(20),
marca VARCHAR(20),
aseguradora VARCHAR(20),
saldo FLOAT,
activo BOOLEAN
);
--INSERTS--
INSERT INTO usuarios VALUES
( '1' , 'GHE45' , 'Christian' , 'H' , '3' , 'christian@gmail.com', '656748394' , 'FORD', 'CAOS', '200' , '1' ),
( '2' , 'GHE42' , 'Maria' , 'M' , '7' , 'Maria@gmail.com', '656748394' , 'FERRARI', 'CAOS', '100' , '0' ),
( '3' , 'JHE43' , 'Paco' , 'H' , '6' , 'Paco@gmail.com', '656748394' , 'PEUGEOT', 'CVAR', '300' , '1' ),
( '4' , 'GHE12' , 'Carla' , 'M' , '2' , 'Carla@gmail.com', '656748394' , 'RENAULT', 'BARD', '10' , '0' ),
( '5' , 'GHE09' , 'Fernando' , 'H' , '8' , 'Fernando@yahoo.com', '656748394' , 'DACIA', 'CARLING', '200' , '1' ),
( '6' , 'GHE35' , 'Rosa' , 'M' , '7' , 'Rosa@gmail.com', '656748394' , 'PORCHE', 'HNOS', '500' , '0' ),
( '7' , 'GHE33' , 'Pedro' , 'H' , '4' , 'Pedro@yahoo.com', '656748394' , 'LAMBORGHINI', 'HERRENOS', '500' , '1' ),
( '8' , 'GHE34' , 'Milena' , 'M' , '5' , 'Milena@gmail.com', '656748394' , 'SEAT', 'MURUA', '2000' , '1' ),
( '9' , 'FHE45' , 'Rosendo' , 'H' , '1' , 'Rosendo@yahoo.com', '656748394' , 'OPEL', 'CRASH', '600' , '0' ),
( '10' , 'RHE45' , 'Paca' , 'M' , '2' , 'Paca@outlook.com', '656748394' , 'OPEL', 'CHOQUETON', '200' , '1' ),
( '11' , 'EHE45' , 'Rodolfo' , 'H' , '3' , 'Rodolfo@gmail.com', '656748394' , 'RENAULT', 'FAVORITA', '20' , '0' ),
( '12' , 'EHG32' , 'Rigoberto' , 'H' , '6' , 'Rigoberto@gmail.com', '656748345' , 'RENAULT', 'FAVORITA', '30' , '1' ),
( '13' , 'RCE45' , 'Josefa' , 'M' , '2' , 'Josefa@outlook.com', '656748395' , 'OPEL', 'CHOQUETON', '0' , '1' ),
( '14' , 'RCE44' , 'Giselle' , 'M' , '2' , 'Giselle@outlook.com', '656748334' , 'OPEL', 'CHOQUETON', '200' , '1' );
--mostrar el maximo saldo de mis clientes mujeres--
SELECT MAX(saldo) FROM usuarios WHERE sexo = 'M';
--mostrar el nombre , telefono de los usuarios que tengan un coche de la marca ford ,renault, dacia--
SELECT nombre,telefono FROM usuarios WHERE marca IN('FORD','RENAULT','DACIA');
--contar usuarios sin saldo y que esten inactivos--
SELECT COUNT(*) FROM usuarios WHERE NOT activo OR saldo <= 0;
--listar el login de los usuarios con nivel 1 ,2 ,3--
SELECT usuario FROM usuarios WHERE nivel IN(1,2,3);
--listar los numeros de telefono con un saldo menor o igual a 300--
SELECT telefono FROM usuarios WHERE saldo<=300;
--sumar los saldos de los usuarios que tengan la compañía FAVORITA--
SELECT SUM(saldo) FROM usuarios WHERE aseguradora= "FAVORITA";
--contar la cantidad de usuarios por compañía aseguradora--
SELECT aseguradora, COUNT(*) FROM usuarios GROUP BY aseguradora;
--listar el login de los usuarios con nivel 2--
SELECT usuario FROM usuarios WHERE nivel = 2;
--mostrar el email de los usuarios que usan gmail--
SELECT email FROM usuarios WHERE email LIKE '%gmail.com';
--cuenta los usuarios que usan yahoo--
SELECT COUNT(*) FROM usuarios WHERE email LIKE '%yahoo.com';
--mostrar el nombre del usuario que tiene un email que empieza por PEDRO--
SELECT nombre FROM usuarios WHERE email LIKE 'Pedro%';
--mostrar el nombre y telefono de los usuarios con coche marca FORD , FERRARI, RENAULT--
SELECT nombre, telefono,marca FROM usuarios WHERE marca IN('FORD', 'FERRARI','RENAULT');
--mostrar los nombres de los usuarios sin saldo o inactivos--
SELECT nombre FROM usuarios WHERE saldo<=0 or NOT activo;
--mostrar el nombre , login y el telefono de los usuarios con aseguradora CHOQUETON O HNOS--
SELECT nombre, usuario, telefono FROM usuarios WHERE aseguradora IN('CHOQUETON', 'HNOS');
--mostrar las diferentoes marcas de coche en ordern alfabético ascendente/descente/aleatorio--
SELECT DISTINCT marca FROM usuarios ORDER BY marca ASC;
SELECT DISTINCT marca FROM usuarios ORDER BY marca DESC;
SELECT DISTINCT marca FROM usuarios ORDER BY RAND();
--mostrar el nombre , login y telefono de los usuarios de las aseguradoras CHOQUETON Y HNOS--
SELECT nombre, usuario, telefono FROM usuarios WHERE aseguradora IN('CHOQUETON','HNOS');
--mostrar el nombre , login y telefono de los usuarios que NO tengan coches de la marca RENAULT,FORD,PEUGEOT,OPEL--
SELECT nombre ,marca, usuario ,telefono FROM usuarios WHERE marca NOT IN('RENAULT','FORD','PEUGEOT','OPEL');
--mostrar el nombre , telefono de los usuarios con coche que no sea RENAULT--
SELECT nombre , telefono FROM usuarios WHERE marca NOT IN('RENAULT');
--mostrar el nombre , telefono de los usuarios con coche que no sea RENAULT , FORD ,OPEL--
SELECT nombre , telefono FROM usuarios WHERE marca NOT IN('RENAULT', 'FORD', 'OPEL');
--mostrar el login y telefono de los usuarios con la aseguradora CHOQUETON--
SELECT usuario telefono FROM usuarios WHERE aseguradora = 'CHOQUETON';
--mostrat las diferentes marcas de coche en orden alfabético descendente--
SELECT DISTINCT marca FROM usuarios ORDER BY marca DESC;
--mostrar las diferentes aseguradoras con un ordern alfabético aleatorio--
SELECT DISTINCT aseguradora FROM usuarios ORDER BY RAND();
--mostrar el login de los usuarios cuyo nivel sea 1 y2;
SELECT usuario FROM usuarios WHERE nivel IN(1,2);
--calcula el saldo promedio de los usuarios que tienen un coche de la marca RENAULT--
SELECT AVG(saldo) FROM usuarios WHERE marca IN('RENAULT');
--mostrar el login de los usuarios con nivel 1 o 3--
SELECT usuario FROM usuarios WHERE nivel IN(1,3);
--mostrar nombre y telefono de los usuarios con coche que no sea de la marca RENAULT--
--modo alternativo--
SELECT nombre , telefono FROM usuarios WHERE marca NOT IN ('RENAULT');
SELECT nombre , telefono FROM usuarios WHERE marca <> ('RENAULT');
--mostrar el login de los usuarios con nivel 3--
SELECT usuario FROM usuarios WHERE nivel = 3;
--contar el numero de usuarios por sexo--
SELECT COUNT(*) FROM usuarios GROUP BY sexo;
--mostrar el login y telefono de los usuarios con la aseguradora FAVORITA--
SELECT usuario ,telefono FROM usuarios WHERE aseguradora = 'FAVORITA';
--mostrar todas las aseguradoras con orden alfabético descendente--
SELECT DISTINCT aseguradora FROM usuarios ORDER BY aseguradora DESC;
--mostrar el login de los usuarios inactivos--
SELECT usuario FROM usuarios WHERE NOT activo;
--mostrar los números de telefono de los socios sin saldo--
SELECT telefono FROM usuarios WHERE saldo <=0;
--calcular el saldo mínimo de los usuarios de sexo "HOMBRE"--
SELECT MIN(saldo) FROM usuarios WHERE sexo = 'H';
--mostrar los numeros de teléfonos de clientes con un saldo mayor a 300--
SELECT telefono FROM usuarios WHERE saldo>300;
--contar el numero de usuarios por la marca de coche--
SELECT COUNT(*) FROM usuarios GROUP BY marca;
--mostrar nombre y telefono de los usuarios con coche que no sea de la marca FORD--
SELECT nombre , telefono FROM usuarios WHERE marca NOT IN('FORD');
--modo alternativo--
SELECT nombre , telefono FROM usuarios WHERE marca <>('FORD');
--mostrar las diferentes compañías en orden alfabético descendente--
SELECT DISTINCT aseguradora FROM usuarios GROUP BY aseguradora DESC;
--calcula la suma de los saldos de los usuarios de la aseguradora CHOQUETON--
SELECT SUM(saldo) FROM usuarios WHERE aseguradora = 'CHOQUETON';
--mostrar el email de los usuarios que usan yahoo.com--
SELECT nombre , email FROM usuarios WHERE email LIKE '%yahoo';
|
CREATE DATABASE database_name;
CREATE TABLE author (
id SERIAL primary key,
firstName VARCHAR(255)
year_of_birth INTEGER,
year_of_death INTEGER DEFAULT 'NaN',
description TEXT,
created_at TIMESTAMP NOT NULL DEFAULT now()
);
|
-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 19-09-2020 a las 18:26:30
-- Versión del servidor: 10.1.39-MariaDB
-- Versión de PHP: 7.3.5
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 */;
--
-- Base de datos: `db_productos`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `categoria`
--
CREATE TABLE `categoria` (
`id_categoria` int(11) NOT NULL,
`nombre` varchar(255) NOT NULL,
`descripcion` varchar(255) NOT NULL,
`origen` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `categoria`
--
INSERT INTO `categoria` (`id_categoria`, `nombre`, `descripcion`, `origen`) VALUES
(1, 'rostro', 'Las cremas faciales de garantizan una hidratación profunda y duradera de la piel. Dejan la piel con una sensación de confort y suavidad.', 'Alemania'),
(2, 'cuerpo', 'Descubre la gama Creme de Corps, inspirada en nuestra clásica Creme de Corps, uno de los productos de culto desde su creación en los años 70. Sus voluptuosas y generosas texturas envuelven tu piel de suavidad y la dejan\r\nsedosa y protegida', 'Alemania'),
(3, 'hombre', 'Cuidar la piel antes y después del afeitado es esencial para tener una piel saludable.', 'Alemania'),
(4, 'cabello', 'Los champús , acondicionadores naturales limpian y nutren el cabello con total delicadeza a la vez que tratan necesidades capilares específicas. Elaborados a base de los mejores ingredientes naturales como el aceite de oliva, aguacate, extracto de limón, ', 'Alemania');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `producto`
--
CREATE TABLE `producto` (
`id_producto` int(11) NOT NULL,
`nombre` varchar(255) NOT NULL,
`descripcion` varchar(255) NOT NULL,
`precio` double NOT NULL,
`categoria` varchar(255) NOT NULL,
`id_categoria` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `producto`
--
INSERT INTO `producto` (`id_producto`, `nombre`, `descripcion`, `precio`, `categoria`, `id_categoria`) VALUES
(1, 'Ultra Facial Cleanser', '\r\nUltra Facial Cleanser es un gel limpiador facial en espuma especialmente formulado para ayudar a eliminar la suciedad y las impurezas sin resecar ni agrietar la piel.', 1850, 'rostro', 1),
(2, 'Calendula Herbal Extract Alcohol-Free Toner', 'Los clientes llevan confiando en Calendula Herbal Extract Alcohol-Free Toner como el tónico natural para pieles grasas y normales favorito desde los años 60. ', 3850, 'rostro', 1),
(3, '\r\nUltra Light Daily UV Defense SPF50 Pa+++\r\n \r\nUltra Light Daily UV Defense SPF50 Pa+++\r\nNOTA \r\n \r\n \r\nAñadir a Favoritos Enviar a un/a amigo/a\r\nUltra Light Daily UV Defense SPF50 Pa+++', 'Loción solar hidratante de alta protección y anti-contaminación de uso diario para el rostro.\r\nProtege tu piel de los primeros signos de envejecimiento producidos por los daños del sol con nuestro SPF 50 PA ++++ de amplio espectro.\r\n', 3600, 'rostro', 1),
(4, 'Ultra Facial Oil-Free Gel Cream', 'Ultra Facial Oil-Free Gel Cream ayuda a reducir el exceso de grasa y a controlar los brillos durante 24 horas\r\nFormulada a partir de extracto de Imperata cylindrica y de antarcticine para facilitar la retención de hidratación\r\n', 2950, 'rostro', 1),
(5, '\r\nVital Skin-Strengthening Super Serum\r\n \r\nVital Skin-Strengthening Super Serum\r\n \r\nVital Skin-Strengthening Super Serum\r\n \r\nVital Skin-Strengthening Super Serum\r\n \r\nVital Skin-Strengthening Super Serum\r\n \r\nVital Skin-Strengthening Super Serum\r\n \r\nVital S', 'Para todos los tipo de piel, incluida la sensible. Súper Sérum Antiedad Ultra- Ligero', 1550, 'rostro', 1);
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `categoria`
--
ALTER TABLE `categoria`
ADD PRIMARY KEY (`id_categoria`);
--
-- Indices de la tabla `producto`
--
ALTER TABLE `producto`
ADD PRIMARY KEY (`id_producto`) USING BTREE,
ADD KEY `id_categoria` (`id_categoria`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `categoria`
--
ALTER TABLE `categoria`
MODIFY `id_categoria` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT de la tabla `producto`
--
ALTER TABLE `producto`
MODIFY `id_producto` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- Restricciones para tablas volcadas
--
--
-- Filtros para la tabla `producto`
--
ALTER TABLE `producto`
ADD CONSTRAINT `producto_ibfk_1` FOREIGN KEY (`id_categoria`) REFERENCES `categoria` (`id_categoria`);
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 */;
|
delimiter //
create procedure userPayments (userId int) begin
select * from listPayments
where idUser=userId;
end //
create procedure getPassengerRoute (sCity varchar(20), dCity varchar(20)) begin
select S.idRoute as idRoute,
S.idCity as idSource,
S.stopNumber as stopSource,
D.idCity as idDest,
D.stopNumber as stopDest
from (
select *
from Stops natural
inner join (
select idCity
from Cities
where nameCity = sCity
) as SC
) as S
inner join (
select *
from Stops natural
inner join (
select idCity
from Cities
where nameCity = dCity
) as DC
) as D on S.idRoute = D.idRoute
where S.stopNumber < D.stopNumber;
end //
create procedure getJourneyRoute (sCity varchar(20), dCity varchar(20)) begin
select S.idRoute as idRoute,
S.idStop as idSource,
D.idStop as idDest
from (
select *
from Stops natural
inner join (
select idCity
from Cities
where nameCity = sCity
) as SC
) as S
inner join (
select *
from Stops natural
inner join (
select idCity
from Cities
where nameCity = dCity
) as DC
) as D on S.idRoute = D.idRoute
where S.stopNumber < D.stopNumber;
end //
create procedure findBuses (Jdate date, busType varchar(20)) begin
select * from listBuses natural inner join (
select idBus
from listBuses
where typeName = busType and idBus not in (
select idBus
from Journey
where JourneyDate = Jdate
)
) as Available
where listBuses.idBus = Available.idBus;
end //
create procedure planJourney(cityS varchar(20), cityD varchar(20), jdate date, bus int, route int, driver int, planner int, dtime time(0)) begin
insert into Journey (startCity,destCity,JourneyDate,idBus,idRoute,idDriver,idAdmin,DepartureTime)
values (cityS, cityD, jdate, bus, route, driver, planner, dtime);
end //
create procedure newUser (emailId varchar(255), passwordString varchar(72), nameIn varchar(60), ageIn int, mobileIn varchar(15), addressIn varchar(60)) begin
insert into Users (email,passwordHash,nameUser,age,mobile_number,addressUser) values (emailId, passwordString, nameIn, ageIn, mobileIn, addressIn);
end //
create procedure addBus (reg_number varchar(10), idType int, odometervalue int) begin
insert into Buses (reg_number_bus,idType,odometer_read) values (reg_number, idType, odometervalue);
end //
create procedure addCity (cityName varchar(20)) begin
insert into Cities (nameCity) values (cityName);
end //
create procedure addRoute (totalDist int, descript varchar(30)) begin
insert into Routes (distanceRoute,descriptionRoute) values (totalDist, descript);
end //
create procedure addDriver (nameIn varchar(60), age int, mobileIn varchar(15), addressIn varchar(60), city varchar(20), licenseNum varchar(15), aadhaarNo char(12), experience char(4)) begin
insert into Drivers (nameDriver,age,mobile_number,addressDriver,city,license_number,aadhaar_number,experience) values (nameIn, age, mobileIn, addressIn, city, licenseNum, aadhaarNo, experience);
end //
create procedure newBooking (userId int) begin
insert into PaymentDetails (statusPayment, methodPayment, idUser)
values ("FAILED", "CASH", userId);
set @idPayDetail = last_insert_id();
insert into Payments (timestampPayment, amountPayment, idPaymentDetails)
values (now(), 0, @idPayDetail);
set @idPayment = last_insert_id();
insert into Bookings (passengers, fareTotal, statusBooking, timestampBooking, idPayment, idUser)
values (0, 0, "Not-Confirmed", now(), @idPayment, userId);
set @idBooking = last_insert_id();
select userId, @idBooking, @idPayment, @idPayDetail;
end //
create procedure addPassenger (bookingId int, journeyId int, namePass varchar(60), agePass int, genPass varchar(6), aadhaarNo varchar(12), sourceCity varchar(20), destCity varchar(20), acPref varchar(6)) begin
set @routeId = (select idRoute from Journey where idJourney=journeyId);
set @busType = (select idType from Buses where idBus=(select Journey.idBus from Journey where idJourney=journeyId));
set @acfare = (select cost_AC from BusTypes where idType=@busType);
set @nonacfare = (select cost_nonAC from BusTypes where idType=@busType);
set @distance = (select distanceFromSource from Stops where idRoute=@routeId and Stops.idCity=(select Cities.idCity from Cities where nameCity=sourceCity)) - (select distanceFromSource from Stops where idRoute=@routeId and idCity=(select Cities.idCity from Cities where nameCity=destCity));
if acPref = "AC" then
set @fare = @acfare;
else
set @fare = @nonacfare;
end if;
insert into Passengers (namePassenger, age, gender, fromCity, toCity, ACtype, farePassenger, aadhaar_number, idBooking, idJourney)
values (namePass, agePass, genPass, sourceCity, destCity, acPref, @fare, aadhaarNo, bookingId, journeyId);
update Bookings set passengers = passengers + 1, fareTotal = fareTotal + @fare, timestampBooking = now()
where idBooking = bookingId;
end //
create procedure updatePayment (bookingId int) begin
update Payments set timestampPayment = now(), amountPayment = (select fareTotal from Bookings where idBooking = bookingId)
where idPayment = (select Bookings.idPayment from Bookings where idBooking = bookingId);
end //
create procedure paymentSuccess (paymentId int, payMethod varchar(16)) begin
update Payments set timestampPayment = now()
where idPayment = paymentId;
update PaymentDetails set statusPayment = "PAID", methodPayment = payMethod
where idPaymentDetails = (select Payments.idPaymentDetails from Payments where idPayment = paymentId);
end //
create procedure paymentReversed (paymentId int, payMethod varchar(16)) begin
update Payments set timestampPayment = now()
where idPayment = paymentId;
update PaymentDetails set statusPayment = "REVERSED", methodPayment = payMethod
where idPaymentDetails = (select Payments.idPaymentDetails from Payments where idPayment = paymentId);
end //
create procedure paymentFailed (paymentId int, payMethod varchar(16)) begin
update Payments set timestampPayment = now()
where idPayment = paymentId;
update PaymentDetails set statusPayment = "FAILED", methodPayment = payMethod
where idPaymentDetails = (select Payments.idPaymentDetails from Payments where idPayment = paymentId);
end //
delimiter ; |
'''
@Coded by TSG, 2021
Problem:
You manage a zoo. Each animal in the zoo comes from a different country. Here are the tables you have:
Animals
https://api.sololearn.com/DownloadFile?id=4534
Countries
https://api.sololearn.com/DownloadFile?id=4533
1) A new animal has come in, with the following details:
name - "Slim", type - "Giraffe", country_id - 1
Add him to the Animals table.
2) You want to make a complete list of the animals for the zoo’s visitors. Write a query to output a new table with each animal's name, type and country fields, sorted by countries.
'''
/*CODE*/
INSERT INTO Animals VALUES ('Slim','Giraffe', 1);
SELECT a.name,a.type,c.country
FROM Animals AS a INNER JOIN Countries AS c
ON a.country_id = c.id
ORDER BY c.country;
|
CREATE DATABASE IF NOT EXISTS `assignment` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `assignment`;
-- MySQL dump 10.13 Distrib 5.7.9, for Win64 (x86_64)
--
-- Host: localhost Database: assignment
-- ------------------------------------------------------
-- Server version 5.7.12-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 `game_genre`
--
DROP TABLE IF EXISTS `game_genre`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `game_genre` (
`game_id` int(11) NOT NULL DEFAULT '9999',
`genre_id` int(11) NOT NULL DEFAULT '9999',
PRIMARY KEY (`game_id`,`genre_id`),
KEY `game_id_idx` (`game_id`),
KEY `genre_id_idx` (`genre_id`),
CONSTRAINT `game_id` FOREIGN KEY (`game_id`) REFERENCES `game` (`game_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `genre_id` FOREIGN KEY (`genre_id`) REFERENCES `genre` (`genre_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `game_genre`
--
LOCK TABLES `game_genre` WRITE;
/*!40000 ALTER TABLE `game_genre` DISABLE KEYS */;
INSERT INTO `game_genre` VALUES (1,2),(1,4),(1,5),(2,1),(2,4),(2,6),(2,8),(3,1),(3,2),(3,3),(3,4),(4,3),(4,4),(4,5),(4,6),(5,1),(5,5),(9999,9999),(10004,1),(10004,2),(10004,4),(10004,7);
/*!40000 ALTER TABLE `game_genre` 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 2016-05-22 17:02:37
|
CREATE TABLE "game" (
"id" serial NOT NULL,
"start_date" TIMESTAMP,
"end_date" TIMESTAMP,
"current_team_id" INT,
CONSTRAINT game_pk PRIMARY KEY ("id")
) WITH (
OIDS=FALSE
);
CREATE TABLE "team" (
"id" serial NOT NULL,
"name" TEXT NOT NULL,
"score" INT NOT NULL,
"game_id" INT NOT NULL,
"current_player_id" INT,
CONSTRAINT result_pk PRIMARY KEY ("id")
) WITH (
OIDS=FALSE
);
CREATE TABLE "player" (
"id" serial NOT NULL,
"name" TEXT NOT NULL,
"team_id" INT NOT NULL,
CONSTRAINT player_pk PRIMARY KEY ("id")
) WITH (
OIDS=FALSE
);
CREATE TABLE "word" (
"id" serial NOT NULL,
"word" TEXT NOT NULL,
CONSTRAINT word_pk PRIMARY KEY ("id")
) WITH (
OIDS=FALSE
);
CREATE TABLE "word_used" (
"game_id" int NOT NULL,
"word_id" int NOT NULL,
CONSTRAINT word_used_pk PRIMARY KEY ("game_id", "word_id")
) WITH (
OIDS=FALSE
);
ALTER TABLE "game" ADD CONSTRAINT "game_fk0" FOREIGN KEY ("current_team_id") REFERENCES "team"("id");
ALTER TABLE "team" ADD CONSTRAINT "team_fk0" FOREIGN KEY ("game_id") REFERENCES "game"("id");
ALTER TABLE "team" ADD CONSTRAINT "team_fk1" FOREIGN KEY ("current_player_id") REFERENCES "player"("id");
ALTER TABLE "player" ADD CONSTRAINT "player_fk0" FOREIGN KEY ("team_id") REFERENCES "team"("id");
ALTER TABLE "word_used" ADD CONSTRAINT "word_used_fk0" FOREIGN KEY ("game_id") REFERENCES "game"("id");
ALTER TABLE "word_used" ADD CONSTRAINT "word_used_fk1" FOREIGN KEY ("word_id") REFERENCES "word"("id");
|
DROP DATABASE if EXISTS TSHH;
CREATE DATABASE TSHH;
USE TSHH;
DROP TABLE IF EXISTS data_dict; /*数据字典*/
DROP TABLE IF EXISTS ts; /*教师学生信息表*/
DROP TABLE IF EXISTS ts_passwd; /*教师学生密码表*/
DROP TABLE IF EXISTS teacher_plan; /*教学计划安排表*/
DROP TABLE IF EXISTS single_class; /*单个班级表*/
DROP TABLE IF EXISTS big_class; /*单个班级组成的大班*/
DROP TABLE IF EXISTS big_class_list; /*每个大班包含的小班*/
DROP TABLE IF EXISTS college; /*学院*/
DROP TABLE IF EXISTS dept; /*专业*/
DROP TABLE IF EXISTS course; /*班级*/
DROP TABLE IF EXISTS schedule_course; /*课表*/
DROP TABLE IF EXISTS datad; /*上传的资料*/
DROP TABLE IF EXISTS download; /*下载的资料*/
DROP TABLE IF EXISTS question; /*问题*/
DROP TABLE IF EXISTS answer; /*答案*/
DROP TABLE IF EXISTS message; /*消息*/
DROP TABLE IF EXISTS rollcall; /*点名记录*/
DROP TABLE IF EXISTS rollcall_nothere; /*点名不在的人*/
DROP TABLE IF EXISTS classroom; /*教室的地图*/
CREATE TABLE data_dict (
dict_id INT NOT NULL AUTO_INCREMENT, /*主键*/
dict_parent_id INT, /*父ID*/
dict_index INT, /*子ID*/
dict_name VARCHAR(200), /*名字*/
dict_value VARCHAR(100) NOT NULL , /*值*/
PRIMARY KEY (dict_id)
);
/*教师学生信息表*/
CREATE TABLE ts (
ts_id INT NOT NULL AUTO_INCREMENT, /*主键*/
ts_num VARCHAR(20), /*老师教工号/学生学号*/
ts_name VARCHAR(20), /*姓名*/
college_id INT, /*所在学院 外键*/
dept_id INT, /*所在系 外键*/
single_class_id INT, /*学生的所在班级 外键*/
ts_introduction VARCHAR(200), /*自我介绍*/
ts_head_image LONGBLOB, /*头像*/
PRIMARY KEY (ts_id)
);
/*教师学生密码表*/
CREATE TABLE ts_passwd (
ts_passwd_id INT NOT NULL AUTO_INCREMENT, /*主键*/
ts_id INT, /*老师学生ID 外键*/
ts_passwd_content CHAR(32), /*密码*/
PRIMARY KEY (ts_passwd_id)
);
/*教学计划安排表*/
CREATE TABLE teacher_plan (
teacher_plan_id INT NOT NULL AUTO_INCREMENT, /*主键*/
ts_id INT, /*老师ID 外键*/
teacher_plan_week INT, /*周 外键*/
classroom_id INT, /*确定教室 外键*/
schedule_course_id INT, /*确定哪一节课 外键*/
teacher_plan_content VARCHAR(1000), /*安排的上课内容,预习内容*/
teacher_plan_type INT, /* 0:上课 1:实验 2:上机 外键 外键*/
PRIMARY KEY (teacher_plan_id)
);
/*单个班级表*/
CREATE TABLE single_class (
single_class_id INT NOT NULL AUTO_INCREMENT, /*主键*/
single_class_name VARCHAR(20), /*班级名称 eg:1404*/
single_class_num INT, /*班级人数 */
dept_id INT, /*所在系 外键*/
college_id INT , /*所在学院 外键*/
PRIMARY KEY (single_class_id)
);
/*单个班级组成的大班*/
CREATE TABLE big_class (
big_class_id INT NOT NULL AUTO_INCREMENT, /*主键*/
big_class_name VARCHAR(40), /*大班名称 */
big_class_people_num INT, /*总人数*/
ts_id INT, /*老师ID 外键*/
course_id INT, /*课程ID 外键*/
PRIMARY KEY (big_class_id)
);
/*大班列表 张根*/
CREATE TABLE big_class_list (
big_class_id INT, /*大班ID 外键*/
single_class_id INT, /*小班ID 外键*/
PRIMARY KEY (big_class_id, single_class_id)
);
/*学院*/
CREATE TABLE college (
college_id INT NOT NULL AUTO_INCREMENT, /*主键*/
college_name VARCHAR(20), /*学院名称*/
college_introduction VARCHAR(1000) , /*学院介绍*/
PRIMARY KEY (college_id)
);
/*专业*/
CREATE TABLE dept (
dept_id INT NOT NULL AUTO_INCREMENT, /*主键*/
college_id INT, /*属于的学院 外键*/
dept_name VARCHAR(20), /*专业名称*/
dept_introduction VARCHAR(1000) , /*专业介绍*/
PRIMARY KEY (dept_id)
);
/*课*/
CREATE TABLE course (
course_id INT NOT NULL AUTO_INCREMENT, /*主键*/
dept_id INT, /*属于的系 外键*/
course_name VARCHAR(20), /*课程名*/
course_introduction VARCHAR(1000) , /*课程介绍*/
PRIMARY KEY (course_id)
);
/*课表*/
CREATE TABLE schedule_course (
schedule_course_id INT NOT NULL AUTO_INCREMENT, /*主键*/
dept_id INT, /*属于的系 外键*/
single_class_id INT, /*属于的班级 外键*/
schedule_course_day INT, /*1-7 分别表示周一到周天 外键*/
schedule_course_course INT, /*1-4 分别标识每天1-4节课 外键*/
classroom_id INT, /*确定每一个教室 外键*/
course_id INT, /*课程 外键*/
PRIMARY KEY (schedule_course_id)
);
/*上传的资料*/
CREATE TABLE datad (
datad_id INT NOT NULL AUTO_INCREMENT, /*主键*/
ts_id INT, /*老师/学生ID 外键*/
course_id INT, /*资料分类 外键*/
datad_uploadtime TIMESTAMP DEFAULT CURRENT_TIMESTAMP, /*资料上传时间*/
datad_size INT, /*资料大小*/
datad_content VARCHAR(200), /*资料的路径*/
datad_downloadtimes INT, /*下载次数*/
PRIMARY KEY (datad_id)
);
/*下载的资料*/
CREATE TABLE download (
download_id INT NOT NULL AUTO_INCREMENT, /*主键*/
datad_id INT, /*确定资料 外键*/
ts_id INT, /*谁下载的 外键*/
download_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, /*下载时间*/
PRIMARY KEY (download_id)
);
/*问题*/
CREATE TABLE question (
question_id INT NOT NULL AUTO_INCREMENT, /*主键*/
ts_id INT, /*提问者 外键*/
question_ask_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, /*问题的提出时间*/
question_content VARCHAR(500), /*问题的内容*/
question_answertimes INT, /*问题的回答个数*/
course_id INT, /*课程ID:问题类型 外键 */
big_class_id INT, /*问题提出的大班ID 外键*/
PRIMARY KEY (question_id)
);
/*答案*/
CREATE TABLE answer (
answer_id INT NOT NULL AUTO_INCREMENT, /*主键*/
ts_id INT, /*回答者的ID 外键*/
question_id INT, /*问题ID 外键*/
answer_content VARCHAR(1000), /*答案内容*/
answer_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, /*问题回答时间*/
PRIMARY KEY (answer_id)
);
/*消息*/
CREATE TABLE message (
message_id INT NOT NULL AUTO_INCREMENT, /*主键*/
message_type INT, /*0:公告 1:回答问题 2:私信 外键*/
ts_id_from INT, /*消息来源 外键*/
ts_id_to INT, /*消息目的 外键*/
message_content VARCHAR(200), /*消息内容*/
message_status INT, /*0:未读 1:已读 外键*/
message_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, /*消息的发送时间*/
PRIMARY KEY (message_id)
);
/*点名记录*/
CREATE TABLE rollcall (
rollcall_id INT NOT NULL AUTO_INCREMENT, /*主键*/
rollcall_week INT, /*周 外键*/
schedule_course_id INT, /*确定哪一节课 外键*/
big_class_id INT, /*大班的ID 外键*/
ts_id INT, /*老师的ID 外键*/
rollcall_yes INT, /*到的人数 */
rollcall_no INT, /*未到的人数 总人数-到了的人数*/
PRIMARY KEY (rollcall_id)
);
/*点名不在的人*/
CREATE TABLE rollcall_nothere (
rollcall_nothere_id INT NOT NULL AUTO_INCREMENT, /*主键*/
rollcall_id INT, /*点名ID 外键*/
ts_id INT, /*学生ID 外键 */
rollcall_nothere_type INT, /*未到状态 -1:缺勤 -2:迟到 */
PRIMARY KEY (rollcall_nothere_id)
);
/*教室的地图*/
CREATE TABLE classroom (
classroom_id INT NOT NULL AUTO_INCREMENT, /*主键*/
classroom_name VARCHAR(20), /*教室名称*/
classroom_way VARCHAR(200), /*教室路径*/
PRIMARY KEY (classroom_id)
);
/*数据字典*/
/*数据字典中的父ID依赖子ID*/
alter table data_dict add constraint FK_super_child_dict foreign key (dict_parent_id)
references data_dict (dict_id) on delete restrict on update restrict;
/*教师学生信息表*/
/*ts表中的colleg_id依赖于college表中的college_id*/
alter table ts add constraint FK_ts_college foreign key (college_id)
references college (college_id) on delete restrict on update restrict;
/*ts表中的dept_id依赖于dept表中的dept_id*/
alter table ts add constraint FK_ts_dept foreign key (dept_id)
references dept (dept_id) on delete restrict on update restrict;
/*ts表中的single_class_id依赖于single_class表中的single_class_id*/
alter table ts add constraint FK_ts_single_class foreign key (single_class_id)
references single_class (single_class_id) on delete restrict on update restrict;
/*教师学生密码表*/
/*ts_passwd表中的ts_id依赖于ts表中的ts_id*/
alter table ts_passwd add constraint FK_ts_passwd_ts foreign key (ts_id)
references ts (ts_id) on delete restrict on update restrict;
/*教学计划安排表*/
/*teacher_plan表中的ts_id依赖于ts表中的ts_id*/
alter table teacher_plan add constraint FK_teacher_plan_ts foreign key (ts_id)
references ts (ts_id) on delete restrict on update restrict;
/*teacher_plan表中的teacher_plan_week依赖于data_dict表中的dict_id*/
alter table teacher_plan add constraint FK_teacher_plan_dict_week foreign key (teacher_plan_week)
references data_dict (dict_id) on delete restrict on update restrict;
/*teacher_plan表中的classroom_id依赖于data_dict表中的dict_id*/
alter table teacher_plan add constraint FK_teacher_plan_dict_classroom foreign key (classroom_id)
references data_dict (dict_id) on delete restrict on update restrict;
/*teacher_plan表中的schedule_course_id依赖于schedule_course表中的schedule_course_id*/
alter table teacher_plan add constraint FK_teacher_plan_schedule foreign key (schedule_course_id)
references schedule_course (schedule_course_id) on delete restrict on update restrict;
/*teacher_plan表中的teacher_plan_type依赖于data_dict表中的dict_id*/
alter table teacher_plan add constraint FK_teacher_plan_dict_class_type foreign key (teacher_plan_type)
references data_dict (dict_id) on delete restrict on update restrict;
/*单个班级表*/
/*single_class表中的dept_id依赖于dept表中的dept_id*/
alter table single_class add constraint FK_single_class_dept foreign key (dept_id)
references dept (dept_id) on delete restrict on update restrict;
/*single_class表中的college_id依赖于college表中的college_id*/
alter table single_class add constraint FK_single_class_college foreign key (college_id)
references college (college_id) on delete restrict on update restrict;
/*单个班级组成的大班*/
/*big_class表中的ts_id依赖于ts表中的ts_id*/
alter table big_class add constraint FK_big_class_ts foreign key (ts_id)
references ts (ts_id) on delete restrict on update restrict;
/*big_class表中的course_id依赖于course表中的course_id*/
alter table big_class add constraint FK_big_class_course foreign key (course_id)
references course (course_id) on delete restrict on update restrict;
/*大班列表*/
/*big_class_list表中的big_class_id依赖于big_class表中的big_class_id*/
alter table big_class_list add constraint FK_big_class_list_big foreign key (big_class_id)
references big_class (big_class_id) on delete restrict on update restrict;
/*big_class_list表中的single_class_id依赖于single_class表中的single_class_id*/
alter table big_class_list add constraint FK_big_class_list_single foreign key (single_class_id)
references single_class (single_class_id) on delete restrict on update restrict;
/*专业*/
/*dept表中的college_id依赖于college表中的college_id*/
alter table dept add constraint FK_dept_college foreign key (college_id)
references college (college_id) on delete restrict on update restrict;
/*课*/
/*course表中的dept_id依赖于dept表中的dept_id*/
alter table course add constraint FK_course_dept foreign key (dept_id)
references dept (dept_id) on delete restrict on update restrict;
/*课表*/
/*schedule_course表中的dept_id依赖于dept表中的dept_id*/
alter table schedule_course add constraint FK_dept_schedule foreign key (dept_id)
references dept (dept_id) on delete restrict on update restrict;
/*schedule_course表中的single_class_id依赖于single_class表中的single_class_id*/
alter table schedule_course add constraint FK_schedule_single_class foreign key (single_class_id)
references single_class (single_class_id) on delete restrict on update restrict;
/*schedule_course表schedule_course_day中的依赖于data_dict表中的dict_id*/
alter table schedule_course add constraint FK_schedule_dict_schedule_course_day foreign key (schedule_course_day)
references data_dict (dict_id) on delete restrict on update restrict;
/*schedule_course表schedule_course_course中的依赖于data_dict表中的dict_id*/
alter table schedule_course add constraint FK_schedule_dict_schedule_course_course foreign key (schedule_course_course)
references data_dict (dict_id) on delete restrict on update restrict;
/*schedule_course表中的classroom_id依赖于classroom表中的classroom_id*/
alter table schedule_course add constraint FK_schedule_classroom foreign key (classroom_id)
references classroom (classroom_id) on delete restrict on update restrict;
/*schedule_course表中的course_id依赖于course表中的course_id*/
alter table schedule_course add constraint FK_schedule_course foreign key (course_id)
references course (course_id) on delete restrict on update restrict;
/*上传的资料*/
/*datad表中的ts_id依赖于ts表中的ts_id*/
alter table datad add constraint FK_datad_ts foreign key (ts_id)
references ts (ts_id) on delete restrict on update restrict;
/*datad表中的course_id依赖于ts表中的course_id*/
alter table datad add constraint FK_datad_course foreign key (course_id)
references course (course_id) on delete restrict on update restrict;
/*下载的资料*/
/*download表中的datad_id依赖于表datad中的datad_id*/
alter table download add constraint FK_download_datad foreign key (datad_id)
references datad (datad_id) on delete restrict on update restrict;
/*download表中的ts_id依赖于表ts中的ts_id*/
alter table download add constraint FK_download_ts foreign key (ts_id)
references ts (ts_id) on delete restrict on update restrict;
/*问题*/
/*question表中的ts_id依赖于表ts中的ts_id*/
alter table question add constraint FK_question_ts foreign key (ts_id)
references ts (ts_id) on delete restrict on update restrict;
/*question表中的course_id依赖于表course中的course_id*/
alter table question add constraint FK_question_course foreign key (course_id)
references course (course_id) on delete restrict on update restrict;
/*question表中的big_class_id依赖于表big_class中的big_class_id*/
alter table question add constraint FK_question_big_class foreign key (big_class_id)
references big_class (big_class_id) on delete restrict on update restrict;
/*答案*/
/*answer表中的ts_id依赖于表ts中的ts_id*/
alter table answer add constraint FK_answer_ts foreign key (ts_id)
references ts (ts_id) on delete restrict on update restrict;
/*answer表中的question_id依赖于表question中的question_id*/
alter table answer add constraint FK_answer_question foreign key (question_id)
references question(question_id) on delete restrict on update restrict;
/*消息*/
/* message表中的ts_id_from依赖于表ts中的ts_id*/
alter table message add constraint FK_message_ts_from foreign key (ts_id_from)
references ts (ts_id) on delete restrict on update restrict;
/* message表中的ts_id_to依赖于表ts中的ts_id*/
alter table message add constraint FK_message_ts_to foreign key (ts_id_to)
references ts (ts_id) on delete restrict on update restrict;
/* message表中的message_type依赖于表data_dict中的dict_id*/
alter table message add constraint FK_message_data_dict_message_type foreign key (message_type)
references data_dict (dict_id) on delete restrict on update restrict;
/* message表中的message_status依赖于表data_dict中的dict_id*/
alter table message add constraint FK_message_data_dict_message_status foreign key (message_status)
references data_dict (dict_id) on delete restrict on update restrict;
/*点名记录*/
/*rollcall表中的big_class_id依赖于表big_class中的big_class_id*/
alter table rollcall add constraint FK_rollcall_big_class foreign key (big_class_id)
references big_class (big_class_id) on delete restrict on update restrict;
/*rollcall表中的ts_id依赖于表ts中的ts_id*/
alter table rollcall add constraint FK_rollcall_ts foreign key (ts_id)
references ts (ts_id) on delete restrict on update restrict;
/*rollcall表中的rollcall_week依赖于表data_dict中的dict_id*/
alter table rollcall add constraint FK_rollcall_data_dict_rollcall_week foreign key (rollcall_week)
references data_dict (dict_id) on delete restrict on update restrict;
/*点名不在的人*/
/*rollcall_nothere表中的rollcall_id依赖于表rollcall中的rollcall_id*/
alter table rollcall_nothere add constraint FK_rollcall_nothere_rollcall foreign key (rollcall_id)
references rollcall (rollcall_id) on delete restrict on update restrict;
/*rollcall_nothere表中的ts_id依赖于表ts中的ts_id*/
alter table rollcall_nothere add constraint FK_rollcall_nothere_ts foreign key (ts_id)
references ts (ts_id) on delete restrict on update restrict;
|
CREATE TABLE Plex.Users
(
UserId INT NOT NULL IDENTITY(1,1),
Identifier UNIQUEIDENTIFIER NOT NULL CONSTRAINT DF_Users_Identifier DEFAULT (NEWID()),
PlexAccountId INT NOT NULL,
Username NVARCHAR(256) NOT NULL,
Email NVARCHAR(256) NOT NULL,
IsAdmin BIT NOT NULL CONSTRAINT DF_Users_IsAdmin DEFAULT (0),
IsDisabled BIT NOT NULL CONSTRAINT DF_Users_IsDisabled DEFAULT (0),
LastLoginUTC DATETIME NULL,
InvalidateTokensBeforeUTC DATETIME NULL,
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_Users_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_Users PRIMARY KEY (UserId),
CONSTRAINT UC_Users_Email UNIQUE(Email),
CONSTRAINT UC_Users_Username UNIQUE(Username),
CONSTRAINT UC_Users_Identifier UNIQUE(Identifier)
)
CREATE TABLE Plex.UserRoles
(
UserRoleId INT NOT NULL IDENTITY(1,1),
UserId INT NOT NULL,
Role NVARCHAR(256) NOT NULL,
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_UserRoles_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_UserRoles PRIMARY KEY (UserRoleId),
CONSTRAINT FK_UserRoles_Users FOREIGN KEY (UserId) REFERENCES Plex.Users (UserId),
CONSTRAINT UC_UserRoles_UserId_Role UNIQUE(UserId, Role)
)
CREATE TABLE Plex.UserRefreshTokens
(
UserRefreshTokenId INT NOT NULL IDENTITY(1,1),
UserId INT NOT NULL,
Token NVARCHAR(MAX) NOT NULL,
ExpiresUTC DATETIME NOT NULL,
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_UserRefreshTokens_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_UserRefreshTokens PRIMARY KEY (UserRefreshTokenId),
CONSTRAINT FK_UserRefreshTokens_Users FOREIGN KEY (UserId) REFERENCES Plex.Users (UserId)
)
CREATE TABLE Plex.PlexServers
(
PlexServerId INT NOT NULL IDENTITY(1,1),
Identifier UNIQUEIDENTIFIER NOT NULL CONSTRAINT DF_PlexServers_Identifier DEFAULT (NEWID()),
Name NVARCHAR(256) NOT NULL,
AccessToken NVARCHAR(2048) NOT NULL,
MachineIdentifier NVARCHAR(1024) NOT NULL,
Scheme NVARCHAR(128) NULL,
LocalIp NVARCHAR(128) NULL,
LocalPort INT NULL,
ExternalIp NVARCHAR(128) NULL,
ExternalPort INT NULL,
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_PlexServers_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_PlexServers PRIMARY KEY (PlexServerId),
CONSTRAINT UC_PlexServers_Name UNIQUE(Name),
CONSTRAINT UC_PlexServers_Identifier UNIQUE(Identifier)
)
CREATE TABLE Plex.PlexLibraries
(
PlexLibraryId INT NOT NULL IDENTITY(1,1),
PlexServerId INT NOT NULL,
LibraryKey NVARCHAR(256) NOT NULL,
[Type] NVARCHAR(256) NOT NULL,
Title NVARCHAR(256) NOT NULL,
IsEnabled BIT NOT NULL CONSTRAINT DF_PlexLibraries_IsEnabled DEFAULT (0),
IsArchived BIT NOT NULL CONSTRAINT DF_PlexLibraries_IsArchived DEFAULT (0),
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_PlexLibraries_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_PlexLibraries PRIMARY KEY (PlexLibraryId),
CONSTRAINT FK_PlexLibraries_PlexServer FOREIGN KEY (PlexServerId) REFERENCES Plex.PlexServers (PlexServerId),
CONSTRAINT UC_PlexLibraries_LibraryKey UNIQUE(PlexServerId, LibraryKey)
)
CREATE TABLE Plex.PlexMediaItems
(
PlexMediaItemId INT NOT NULL IDENTITY(1,1),
Identifier UNIQUEIDENTIFIER NOT NULL CONSTRAINT DF_PlexMediaItems_Identifier DEFAULT (NEWID()),
PlexLibraryId INT NOT NULL,
MediaItemKey INT NOT NULL,
Title NVARCHAR(256) NOT NULL,
AgentTypeId INT NOT NULL,
AgentSourceId NVARCHAR(256),
MediaUri NVARCHAR(2048) NULL,
[Year] INT NULL,
Resolution NVARCHAR(256) NULL,
MediaTypeId INT NOT NULL,
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_PlexMediaItems_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_PlexMediaItems PRIMARY KEY (PlexMediaItemId),
CONSTRAINT FK_PlexMediaItems_PlexLibraries FOREIGN KEY (PlexLibraryId) REFERENCES Plex.PlexLibraries (PlexLibraryId),
CONSTRAINT FK_PlexMediaItems_AgentTypes FOREIGN KEY (AgentTypeId) REFERENCES Plex.AgentTypes (AgentTypeId),
CONSTRAINT FK_PlexMediaItems_MediaTypes FOREIGN KEY (MediaTypeId) REFERENCES Plex.MediaTypes (MediaTypeId),
CONSTRAINT UC_PlexMediaItems_Identifier UNIQUE(Identifier),
CONSTRAINT UC_PlexMediaItems_Key UNIQUE(PlexLibraryId, MediaItemKey)
)
CREATE TABLE Plex.PlexSeasons
(
PlexSeasonId INT NOT NULL IDENTITY(1,1),
Identifier UNIQUEIDENTIFIER NOT NULL CONSTRAINT DF_PlexSeasons_Identifier DEFAULT (NEWID()),
PlexMediaItemId INT NOT NULL,
Season INT NOT NULL,
MediaItemKey INT NOT NULL,
Title NVARCHAR(256) NOT NULL,
AgentTypeId INT NOT NULL,
AgentSourceId NVARCHAR(256) NULL,
MediaUri NVARCHAR(2048) NULL,
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_PlexSeasons_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_PlexSeasons PRIMARY KEY (PlexSeasonId),
CONSTRAINT FK_PlexSeasons_PlexMediaItems FOREIGN KEY (PlexMediaItemId) REFERENCES Plex.PlexMediaItems (PlexMediaItemId),
CONSTRAINT FK_PlexSeasons_AgentTypes FOREIGN KEY (AgentTypeId) REFERENCES Plex.AgentTypes (AgentTypeId),
CONSTRAINT UC_PlexSeasons_Season UNIQUE(PlexMediaItemId, Season),
CONSTRAINT UC_PlexSeasons_Identifier UNIQUE(Identifier)
)
CREATE TABLE Plex.PlexEpisodes
(
PlexEpisodeId INT NOT NULL IDENTITY(1,1),
Identifier UNIQUEIDENTIFIER NOT NULL CONSTRAINT DF_PlexEpisodes_Identifier DEFAULT (NEWID()),
PlexSeasonId INT NOT NULL,
Episode INT NOT NULL,
Year INT NULL,
Resolution NVARCHAR(256) NULL,
MediaItemKey INT NOT NULL,
Title NVARCHAR(256) NOT NULL,
AgentTypeId INT NOT NULL,
AgentSourceId NVARCHAR(256) NULL,
MediaUri NVARCHAR(2048) NULL,
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_PlexEpisodes_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_PlexEpisodes PRIMARY KEY (PlexEpisodeId),
CONSTRAINT FK_PlexEpisodes_PlexSeasons FOREIGN KEY (PlexSeasonId) REFERENCES Plex.PlexSeasons (PlexSeasonId),
CONSTRAINT FK_PlexEpisodes_AgentTypes FOREIGN KEY (AgentTypeId) REFERENCES Plex.AgentTypes (AgentTypeId),
CONSTRAINT UC_PlexEpisodes_Episode UNIQUE(PlexSeasonId, Episode),
CONSTRAINT UC_PlexEpisodes_Identifier UNIQUE(Identifier)
)
CREATE TABLE Plex.MovieRequests
(
MovieRequestId INT IDENTITY(1,1) NOT NULL,
TheMovieDbId INT NOT NULL,
PlexMediaItemId INT NULL,
UserId INT NOT NULL,
Title NVARCHAR(256) NOT NULL,
RequestStatusId INT NOT NULL,
ImagePath NVARCHAR(2048) NULL,
AirDateUTC DATETIME NULL,
Comment NVARCHAR(1024) NULL,
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_MovieRequests_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_MovieRequests PRIMARY KEY (MovieRequestId),
CONSTRAINT FK_MovieRequests_Users FOREIGN KEY (UserId) REFERENCES Plex.Users (UserId),
CONSTRAINT UC_MovieRequests_TheMovieDb_User UNIQUE(TheMovieDbId, UserId)
)
CREATE TABLE Plex.MovieRequestAgents
(
MovieRequestAgentId INT IDENTITY(1,1) NOT NULL,
MovieRequestId INT NOT NULL,
AgentTypeId INT NOT NULL,
AgentSourceId NVARCHAR(256) NOT NULL,
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_MovieRequestAgents_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_MovieRequestAgents PRIMARY KEY (MovieRequestAgentId),
CONSTRAINT FK_MovieRequestAgents_MovieRequests FOREIGN KEY (MovieRequestId) REFERENCES Plex.MovieRequests (MovieRequestId),
CONSTRAINT FK_MovieRequestAgents_AgentTypes FOREIGN KEY (AgentTypeId) REFERENCES Plex.AgentTypes (AgentTypeId),
CONSTRAINT UC_MovieRequestAgents_MovieRequest_AgentType UNIQUE(MovieRequestId, AgentTypeId)
)
CREATE TABLE Plex.TvRequests
(
TvRequestId INT IDENTITY(1,1) NOT NULL,
TheMovieDbId INT NOT NULL,
PlexMediaItemId INT NULL,
Title NVARCHAR(256) NOT NULL,
RequestStatusId INT NOT NULL,
ImagePath NVARCHAR(2048) NULL,
AirDateUTC DATETIME NULL,
Comment NVARCHAR(1024) NULL,
Track BIT NOT NULL CONSTRAINT DF_TvRequests_Track DEFAULT (0),
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_TvRequests_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_TvRequests PRIMARY KEY (TvRequestId),
CONSTRAINT FK_TvRequests_PlexMediaItems FOREIGN KEY (PlexMediaItemId) REFERENCES Plex.PlexMediaItems (PlexMediaItemId),
CONSTRAINT FK_TvRequests_RequestStatus FOREIGN KEY (RequestStatusId) REFERENCES Plex.RequestStatuses (RequestStatusId),
CONSTRAINT UC_TvRequests_TheMovieDb_User UNIQUE(TheMovieDbId, Track)
)
CREATE TABLE Plex.TvRequestAgents
(
TvRequestAgentId INT IDENTITY(1,1) NOT NULL,
TvRequestId INT NOT NULL,
AgentTypeId INT NOT NULL,
AgentSourceId NVARCHAR(256) NOT NULL,
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_TvRequestAgents_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_TvRequestAgents PRIMARY KEY (TvRequestAgentId),
CONSTRAINT FK_TvRequestAgents_TvRequests FOREIGN KEY (TvRequestId) REFERENCES Plex.TvRequests (TvRequestId),
CONSTRAINT FK_TvRequestAgents_AgentTypes FOREIGN KEY (AgentTypeId) REFERENCES Plex.AgentTypes (AgentTypeId),
CONSTRAINT UC_TvRequestAgents_TvRequest_AgentType UNIQUE(TvRequestId, AgentTypeId)
)
CREATE TABLE Plex.TvRequestSeasons
(
TvRequestSeasonId INT IDENTITY(1,1) NOT NULL,
TvRequestId INT NOT NULL,
PlexSeasonId INT NULL,
SeasonIndex INT NOT NULL,
RequestStatusId INT NOT NULL,
ImagePath NVARCHAR(2048) NULL,
AirDateUTC DATETIME NULL,
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_TvRequestSeasons_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_TvRequestSeasons PRIMARY KEY (TvRequestSeasonId),
CONSTRAINT FK_TvRequestSeasons_TvRequests FOREIGN KEY (TvRequestId) REFERENCES Plex.TvRequests (TvRequestId),
CONSTRAINT FK_TvRequestSeasons_PlexMediaSeasons FOREIGN KEY (PlexSeasonId) REFERENCES Plex.PlexSeasons (PlexSeasonId),
CONSTRAINT FK_TvRequestSeasons_RequestStatus FOREIGN KEY (RequestStatusId) REFERENCES Plex.RequestStatuses (RequestStatusId),
CONSTRAINT UC_TvRequestSeasons_Season UNIQUE(TvRequestId, SeasonIndex)
)
CREATE TABLE Plex.TvRequestEpisodes
(
TvRequestEpisodeId INT IDENTITY(1,1) NOT NULL,
TvRequestSeasonId INT NOT NULL,
PlexEpisodeId INT NULL,
EpisodeIndex INT NOT NULL,
RequestStatusId INT NOT NULL,
ImagePath NVARCHAR(2048) NULL,
AirDateUTC DATETIME NULL,
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_TvRequestEpisodes_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_TvRequestEpisodes PRIMARY KEY (TvRequestEpisodeId),
CONSTRAINT FK_TvRequestEpisodes_TvRequestSeasons FOREIGN KEY (TvRequestSeasonId) REFERENCES Plex.TvRequestSeasons (TvRequestSeasonId),
CONSTRAINT FK_TvRequestEpisodes_PlexEpisodes FOREIGN KEY (PlexEpisodeId) REFERENCES Plex.PlexEpisodes (PlexEpisodeId),
CONSTRAINT FK_TvRequestEpisodes_RequestStatus FOREIGN KEY (RequestStatusId) REFERENCES Plex.RequestStatuses (RequestStatusId),
CONSTRAINT UC_TvRequestEpisodes_Season UNIQUE(TvRequestSeasonId, EpisodeIndex)
)
CREATE TABLE Plex.TvRequestUsers
(
TvRequestUserId INT IDENTITY(1,1) NOT NULL,
TvRequestId INT NOT NULL,
UserId INT NOT NULL,
Season INT NULL,
Episode INT NULL,
Track INT NOT NULL CONSTRAINT DF_TvRequestUsers_Track DEFAULT (0),
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_TvRequestUsers_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_TvRequestUsers PRIMARY KEY (TvRequestUserId),
CONSTRAINT FK_TvRequestUsers_TvRequests FOREIGN KEY (TvRequestId) REFERENCES Plex.TvRequests (TvRequestId),
CONSTRAINT FK_TvRequestUsers_Users FOREIGN KEY (UserId) REFERENCES Plex.Users (UserId),
CONSTRAINT UC_TvRequestUsers_SingleRequest UNIQUE(TvRequestId, UserId, Season, Episode)
)
CREATE TABLE Plex.Issues
(
IssueId INT IDENTITY(1,1) NOT NULL,
PlexMediaItemId INT NOT NULL,
UserId INT NOT NULL,
Title NVARCHAR(256),
Description NVARCHAR(MAX) NOT NULL,
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_Issues_CreatedUTC DEFAULT(GETUTCDATE()),
IssueStatusId INT NOT NULL,
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_Issues PRIMARY KEY (IssueId),
CONSTRAINT FK_Issues_PlexMediaItems FOREIGN KEY (PlexMediaItemId) REFERENCES Plex.PlexMediaItems (PlexMediaItemId),
CONSTRAINT FK_Issues_Users FOREIGN KEY (UserId) REFERENCES Plex.Users (UserId),
CONSTRAINT UC_Issue_User_PlexMediaItem UNIQUE (PlexMediaItemId, UserId)
)
CREATE TABLE Plex.IssueComments
(
IssueCommentId INT IDENTITY(1,1) NOT NULL,
IssueId INT NOT NULL,
UserId INT NOT NULL,
Comment NVARCHAR(MAX),
LikeCount INT NOT NULL CONSTRAINT DF_IssueComments_LikeCount DEFAULT (0),
CreatedUTC DATETIME NOT NULL CONSTRAINT DF_IssueComments_CreatedUTC DEFAULT(GETUTCDATE()),
UpdatedUTC DATETIME NULL,
CONSTRAINT PK_IssueComments PRIMARY KEY (IssueCommentId),
CONSTRAINT FK_IssueComments_Issues FOREIGN KEY (IssueId) REFERENCES Plex.Issues (IssueId),
CONSTRAINT FK_IssueComments_Users FOREIGN KEY (UserId) REFERENCES Plex.Users (UserId),
)
|
-- Movies without any stars
SELECT id AS 'Movie ID', title AS 'Movie Title', year AS 'Movie Year' FROM movies WHERE id NOT IN(SELECT movie_id AS id FROM stars_in_movies);
-- Stars without any movies
SELECT id AS 'Star ID', first_name AS 'Star First Name', last_name AS 'Star Last Name' FROM stars WHERE id NOT IN (SELECT star_id AS id FROM stars_in_movies);
-- Genres without any movies
SELECT id AS 'Genre ID', name AS 'Genre Name' FROM genres WHERE id NOT IN (SELECT genre_id AS id FROM genres_in_movies);
-- Movies without any genres
SELECT id AS 'Movie ID', title AS 'Movie Title', year AS 'Movie Year' FROM movies WHERE id NOT IN (SELECT movie_id AS id FROM genres_in_movies);
-- Stars without first name or last name
SELECT id AS 'Star ID', first_name AS 'Star First Name', last_name AS 'Star Last Name' FROM stars WHERE first_name = '' OR last_name = '';
-- Expired Customer Credit Cards
SELECT c.id AS 'Customer ID', c.first_name AS 'Customer First Name', c.last_name AS 'Customer Last Name', c.cc_id AS 'Credit Card Number', cc.expiration AS 'Credit Card Expiration Date 'FROM customers AS c, creditcards AS cc WHERE c.cc_id = cc.id AND cc.expiration < CURDATE();
-- Duplicate Movies
SELECT m.* FROM movies AS m WHERE m.id IN (SELECT id FROM movies GROUP BY title, year HAVING COUNT(*) > 1);
-- Duplicate Stars
SELECT s.* FROM stars AS s WHERE s.id IN (SELECT id FROM stars GROUP BY first_name, last_name HAVING COUNT(*) > 1);
-- Duplicate Genres
SELECT g.* FROM genres AS g WHERE g.id IN (SELECT id FROM genres GROUP BY name HAVING COUNT(*) > 1);
-- Birthday Filter
SELECT * FROM stars WHERE YEAR(dob) < 1900 OR dob > CURDATE();
-- Email Filter
SELECT c.* from customers AS c WHERE c.id NOT IN (SELECT id FROM customers WHERE email LIKE '%@%'); |
CREATE Procedure sp_update_ColorSettings
(@ITEMS NVARCHAR (50),
@BACKCOLOR INTEGER,
@FORECOLOR INTEGER)
AS
Update ColorSettings Set BackColor = @BACKCOLOR,ForeColor=@FORECOLOR where Items=@ITEMS
|
ALTER TABLE FAGSAK_PERSON
ADD CONSTRAINT FK_FAGSAK_ID_FAGSAK_PERSON FOREIGN KEY (FK_FAGSAK_ID) REFERENCES FAGSAK (ID); |
CREATE TABLE matches (
DateCreated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
DateUpdated TIMESTAMP DEFAULT NULL,
MatchSid varchar(36),
TournamentSid varchar(36),
BracketSid varchar(36),
PrimaryTeam varchar(36),
SecondaryTeam varchar(36),
State tinyint,
ScheduledTime datetime
); |
DROP TABLE IF EXISTS products;
CREATE TABLE products (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
description VARCHAR(100) NOT NULL,
price FLOAT NOT NULL,
inventory INTEGER NOT NULL,
CONSTRAINT PK_PRODUCT PRIMARY KEY(id)
); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.