text stringlengths 6 9.38M |
|---|
create table ANIMAIS(
COD varchar primary key,
nome varchar,
ano_nasc varchar,
setor varchar,
especie varchar,
obs varchar,
peso varchar,
ultima_visita_vet varchar
);
-----------------------------------------------------------
create table FUNCIONARIOS(
PIS varchar primary key,
nome varchar,
carga_horaria varchar,
salario varchar,
email varchar,
CPF varchar,
cargo varchar,
data_nasc varchar
);
-----------------------------------------------------------
create table FORNECEDOR(
CNPJ varchar primary key,
local varchar,
email varchar,
produto varchar
);
-----------------------------------------------------------
create table ESTOQUE(
cod_fornecedor varchar references FORNECEDOR(CNPJ),
data_compra varchar,
marca varchar,
QTD varchar,
preco int,
validade varchar,
produto varchar,
COD varchar primary key
);
-----------------------------------------------------------
create table ALIMENTAM(
cod_animais varchar references ANIMAIS(COD),
cod_estoque varchar references ESTOQUE(COD)
);
-----------------------------------------------------------
create table CUIDAM(
cod_funcionario varchar references FUNCIONARIOS(PIS),
cod_animal varchar references ANIMAIS (COD)
);
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
create table VISITANTES(
CPF varchar primary key,
idade varchar,
nome varchar,
checkin varchar
);
-----------------------------------------------------------
create table BILHETERIA(
cod_visitantes varchar references VISITANTES(CPF),
esta_zoo boolean,
n_pulseira varchar primary key
);
-----------------------------------------------------------
-----------------------------------------------------------
create table CONTAS(
COD varchar primary key,
valor_total_estoque varchar,
mes_ano varchar,
valor_total_bilheteria varchar,
valor_total_funcionarios varchar,
gastos_extras varchar,
lucro varchar
);
-----------------------------------------------------------
create table EMPRESAS_PARCEIRAS(
COD varchar primary key,
email varchar,
funcao varchar,
nome varchar,
aluguel varchar
);
-----------------------------------------------------------
|
/* Script to setup mysql users and the database structure. */
DROP DATABASE IF EXISTS website;
CREATE DATABASE website;
CREATE USER website IDENTIFIED BY "coffeesforclosers";
GRANT ALL PRIVILEGES ON website.* TO website@localhost;
USE website;
CREATE TABLE posts (
post_id int not null auto_increment,
post_date datetime not null,
post_title varchar(100),
post_description varchar(250),
post_filename varchar(100),
PRIMARY KEY (post_id)
) ENGINE = InnoDB;
CREATE TABLE tags (
post_id int not null,
tag_name varchar(50) not null,
PRIMARY KEY (post_id, tag_name),
FOREIGN KEY (post_id) REFERENCES posts(post_id) ON DELETE CASCADE
) ENGINE = InnoDB;
INSERT INTO posts (post_id, post_title, post_date, post_description, post_filename)
VALUES (1, "Test Post", "2015-3-15 10:53:00", "Please Ignore.", "test.md");
INSERT INTO posts (post_id, post_title, post_date, post_description, post_filename)
VALUES (2, "Pest Toast", "2015-3-1 11:32:00", "pls ignore", "test2.md");
INSERT INTO tags (post_id, tag_name)
VALUES ("1", "test");
INSERT INTO tags (post_id, tag_name)
VALUES ("2", "toast"); |
INSERT INTO products ("title", "description", "price") VALUES
('Animal Crossing: New Horizons', 'Escape to a deserted island and create your own paradise as you explore, create, and customize in the Animal Crossing: New Horizons game', 59.99),
('The Legend of Zelda: Breath of the Wild', 'Step into a world of discovery, exploration, and adventure in The Legend of Zelda: Breath of the Wild, a boundary-breaking new game in the acclaimed series.', 40),
('Bayonetta', 'The last survivor of an ancient witch clan who keep the balance between light, dark and chaos.', 55),
('Mario', 'Mario Kart is a series of go-kart-style racing video games developed and published by Nintendo as spin-offs from its trademark Super Mario series', 30),
('Fortnite', 'Fortnite is a free-to-play video game set in a post-apocalyptic, zombie-infested world', 24),
('Owerwatch', 'Overwatch is a team-based multiplayer first-person shooter developed and published by Blizzard Entertainment.', 35),
('Dark Souls', 'Then, there was fire. Re-experience the critically acclaimed, genre-defining game that started it all.', 55)
INSERT INTO stocks ("product_id", "count") VALUES
('a4b71d83-d0d2-4b8f-89ea-981f737ab69e', 3),
('7ba98000-28f8-40b0-b783-b6b308576d58', 6),
('c4bfcfd2-b237-475f-8a09-451a056a4b1e', 7),
('d2194c8d-bb4a-44c9-874d-9cce8ac45dbb', 9),
('64066b78-03af-4a6f-adfe-7bc762fe1d60', 5),
('d764d266-2900-43a6-9c58-6e10d3d36bc5', 11),
('18104db6-cf71-4974-be4c-91a6aaf6f608', 1) |
/*
Navicat MySQL Data Transfer
Source Server : 本机
Source Server Version : 50717
Source Host : localhost:3306
Source Database : mpts
Target Server Type : MYSQL
Target Server Version : 50717
File Encoding : 65001
Date: 2018-03-13 20:41:58
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for system_admin_account
-- ----------------------------
DROP TABLE IF EXISTS `system_admin_account`;
CREATE TABLE `system_admin_account` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`username` varchar(64) CHARACTER SET utf8 NOT NULL COMMENT '用户名',
`password` varchar(255) CHARACTER SET utf8 NOT NULL COMMENT '密码',
`mobile` varchar(20) CHARACTER SET utf8 DEFAULT NULL COMMENT '电话',
`phone` varchar(20) CHARACTER SET utf8 DEFAULT NULL COMMENT '手机号',
`email` varchar(64) CHARACTER SET utf8 DEFAULT NULL COMMENT '电子邮件',
`company_code` varchar(50) DEFAULT NULL COMMENT '公司编码',
`is_used` tinyint(4) DEFAULT NULL COMMENT '是否使用:0禁用1恢复',
`create_date` datetime DEFAULT NULL COMMENT '创建时间',
`create_by` varchar(32) DEFAULT NULL COMMENT '由谁创建',
`update_date` datetime DEFAULT NULL COMMENT '修改时间',
`update_by` varchar(32) DEFAULT NULL COMMENT '由谁修改',
`is_deleted` varchar(1) DEFAULT NULL COMMENT '是否删除:0 未删除 1删除',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2488 DEFAULT CHARSET=latin1 COMMENT='用户表';
-- ----------------------------
-- Records of system_admin_account
-- ----------------------------
INSERT INTO `system_admin_account` VALUES ('1', 'admin', '113765b146867037b814a8ef1c2ec35d73bfb77c8d27a5f1a520099f5949cfaa', null, '13233332222', '123456789@qq.com', 'JBH', '1', '2016-08-22 11:25:40', '1', '2018-02-06 18:50:27', '1', '0');
-- ----------------------------
-- Table structure for system_admin_role
-- ----------------------------
DROP TABLE IF EXISTS `system_admin_role`;
CREATE TABLE `system_admin_role` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`admin_id` int(11) NOT NULL COMMENT '管理员id',
`role_id` int(11) NOT NULL COMMENT '角色id',
`create_time` datetime NOT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=252 DEFAULT CHARSET=latin1 COMMENT='用户角色表';
-- ----------------------------
-- Records of system_admin_role
-- ----------------------------
INSERT INTO `system_admin_role` VALUES ('1', '1', '1', '2016-06-25 15:46:32');
-- ----------------------------
-- Table structure for system_dict
-- ----------------------------
DROP TABLE IF EXISTS `system_dict`;
CREATE TABLE `system_dict` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`dict_code` varchar(64) DEFAULT NULL COMMENT '字典编码',
`dict_name` varchar(255) DEFAULT NULL COMMENT '字典名称',
`parent_id` varchar(64) DEFAULT NULL COMMENT '父节点编码',
`status` varchar(10) DEFAULT NULL COMMENT '字典状态(0,启用1,禁用)',
`create_date` datetime NOT NULL COMMENT '创建时间',
`create_by` varchar(32) DEFAULT NULL COMMENT '创建人',
`update_date` datetime DEFAULT NULL COMMENT '更新时间',
`update_by` varchar(32) DEFAULT NULL COMMENT '更新人',
`is_deleted` char(1) NOT NULL COMMENT '使用状态(0未删除 1删除)',
`comment` varchar(255) DEFAULT NULL COMMENT '说明',
`level` tinyint(4) DEFAULT NULL COMMENT '0-组,1-组中数据',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='字典表';
-- ----------------------------
-- Records of system_dict
-- ----------------------------
INSERT INTO `system_dict` VALUES ('3', 'x', 'x', null, '0', '2018-03-13 20:34:57', '1', null, null, '1', null, '0');
-- ----------------------------
-- Table structure for system_resource
-- ----------------------------
DROP TABLE IF EXISTS `system_resource`;
CREATE TABLE `system_resource` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`name` varchar(64) NOT NULL COMMENT '资源名',
`url` varchar(512) DEFAULT NULL COMMENT '资源url',
`type` tinyint(4) NOT NULL COMMENT '资源类型(1.菜单,2.按钮)',
`level` tinyint(4) DEFAULT NULL COMMENT '资源级别',
`path` varchar(512) DEFAULT NULL COMMENT '资源Path',
`parent_id` int(11) DEFAULT NULL COMMENT '父级别id',
`create_time` datetime NOT NULL COMMENT '创建时间',
`update_time` datetime NOT NULL COMMENT '记录更新日期',
`is_used` tinyint(4) NOT NULL COMMENT '是否使用',
`comment` varchar(255) DEFAULT NULL COMMENT '说明',
`order` int(11) DEFAULT NULL,
`icon` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=603 DEFAULT CHARSET=utf8 COMMENT='系统-资源表';
-- ----------------------------
-- Records of system_resource
-- ----------------------------
INSERT INTO `system_resource` VALUES ('1', '登陆', '/login', '0', '0', '', '0', '2016-06-13 09:56:52', '2016-06-13 09:56:54', '1', null, '1', null);
INSERT INTO `system_resource` VALUES ('2', '退出', '/logout', '0', '0', null, '0', '2016-06-13 09:57:27', '2016-06-13 09:57:30', '1', null, '2', null);
INSERT INTO `system_resource` VALUES ('3', '首页', '/index', '0', '0', null, '0', '2016-06-13 09:58:50', '2016-06-13 09:58:54', '1', null, '3', null);
INSERT INTO `system_resource` VALUES ('4', '系统管理', '', '1', '1', '/4/', '0', '2016-06-13 10:03:20', '2017-05-02 17:15:59', '1', null, '999999', '<i class=\"fa fa-cog\"></i>');
INSERT INTO `system_resource` VALUES ('5', '用户管理', '/system/admin/list', '1', '2', '/4/5/', '4', '2016-06-13 10:04:27', '2016-07-05 16:33:59', '1', '备注', '4', null);
INSERT INTO `system_resource` VALUES ('10', '角色管理', '/system/role/list', '1', '2', '/4/10/', '4', '2016-06-13 10:13:05', '2016-06-27 15:09:01', '1', '备注', '10', null);
INSERT INTO `system_resource` VALUES ('14', '资源管理', '/system/resource/list', '1', '2', '/4/14/', '4', '2016-06-13 10:38:53', '2016-06-27 15:09:01', '1', null, '14', null);
INSERT INTO `system_resource` VALUES ('24', '头部', '/head', '0', '0', null, '0', '2016-06-15 15:58:55', '2016-06-15 15:58:58', '0', null, '9', null);
INSERT INTO `system_resource` VALUES ('25', '菜单', '/menu', '0', '0', null, '0', '2016-06-15 15:59:40', '2016-06-23 15:59:43', '0', null, '10', null);
INSERT INTO `system_resource` VALUES ('165', '分配权限', '/system/resource/allotResource', '2', '3', '/4/14/165', '14', '2016-06-24 17:10:38', '2016-06-24 17:10:41', '1', null, '165', null);
INSERT INTO `system_resource` VALUES ('166', '去分配权限', '/system/resource/toAllotResource', '2', '3', '/4/14/166', '14', '2016-06-24 17:10:43', '2016-06-24 17:10:46', '1', null, '166', null);
INSERT INTO `system_resource` VALUES ('167', '编辑权限', '/system/resource/toEdit', '2', '3', '/4/14/167', '14', '2016-06-25 14:46:19', '2016-06-25 14:46:21', '1', '14', '167', null);
INSERT INTO `system_resource` VALUES ('168', '保存权限', '/system/resource/save', '2', '3', '/4/14/168', '14', '2016-06-24 18:00:03', '2016-06-24 18:00:06', '1', null, '168', null);
INSERT INTO `system_resource` VALUES ('169', '删除权限', '/system/resource/deleteResource', '2', '3', '/4/14/169', '14', '2016-06-24 18:01:10', '2016-06-27 13:27:24', '1', null, '169', null);
INSERT INTO `system_resource` VALUES ('170', '排序权限', '/system/resource/orderResource', '2', '3', '/4/14/170', '14', '2016-06-24 18:03:21', '2016-06-27 13:27:24', '1', null, '170', null);
INSERT INTO `system_resource` VALUES ('171', '编辑角色', '/system/role/toEdit', '2', '3', '/4/10/171', '10', '2016-06-24 18:07:34', '2017-06-15 14:06:54', '1', '跳转到编辑角色页面', '172', null);
INSERT INTO `system_resource` VALUES ('172', '保存角色', '/system/role/save', '2', '3', '/4/10/172', '10', '2016-06-24 18:08:45', '2017-03-23 17:46:21', '1', '保存角色', '171', null);
INSERT INTO `system_resource` VALUES ('173', '删除角色', '/system/role/deleteRole', '2', '3', '/4/10/173', '10', '2016-06-24 18:08:47', '2017-03-24 13:21:06', '1', '删除角色', '173', null);
INSERT INTO `system_resource` VALUES ('174', '编辑用户', '/system/admin/toEdit', '2', '3', '/4/5/174', '5', '2016-06-24 18:11:37', '2017-06-15 13:59:51', '1', '跳转到编辑用户页面', '174', null);
INSERT INTO `system_resource` VALUES ('175', '保存用户', '/system/admin/save', '2', '3', '/4/5/175', '5', '2016-06-24 18:12:17', '2017-06-23 11:10:35', '1', '保存用户', '175', '<i class=\"fa fa-legal\"></i>');
INSERT INTO `system_resource` VALUES ('176', '删除用户', '/system/admin/deleteUser', '2', '3', '/4/5/176', '5', '2016-06-24 18:13:21', '2017-06-23 11:10:48', '1', '删除用户', '176', null);
INSERT INTO `system_resource` VALUES ('181', '主页面', '/main', '0', '0', '', '0', '2016-08-11 00:00:00', '2016-08-11 00:00:00', '1', '主页面', '6', null);
INSERT INTO `system_resource` VALUES ('238', '执行添加', '/system/admin/getUserByName', '2', '3', '/4/5/238/', '5', '2016-11-22 11:05:57', '2016-11-22 11:05:57', '1', '/system/admin/getUserByName', '238', null);
INSERT INTO `system_resource` VALUES ('273', '添加用户', '/system/admin/toAdd', '2', '3', '/4/5/273/', '5', '2017-03-23 17:29:34', '2017-06-15 13:59:06', '1', '跳转到添加用户界面', '273', null);
INSERT INTO `system_resource` VALUES ('274', '添加角色', '/system/role/toAddRole', '2', '3', '/4/10/274/', '10', '2017-03-23 17:41:34', '2017-06-15 14:06:24', '1', '跳转到添加角色页面', '274', null);
INSERT INTO `system_resource` VALUES ('275', '验证角色', '/system/role/getRoleByName', '2', '3', '/4/10/275/', '10', '2017-03-23 17:47:17', '2017-03-23 17:47:17', '1', '校验角色是否存在', '275', null);
INSERT INTO `system_resource` VALUES ('276', '保存编辑用户', '/system/admin/editUser', '2', '3', '/4/5/276/', '5', '2017-03-23 18:08:55', '2017-03-23 18:08:55', '1', '保存编辑用户', '276', null);
INSERT INTO `system_resource` VALUES ('283', '禁用用户', '/system/admin/disabledAdmin', '2', '3', '/4/5/283/', '5', '2017-03-24 13:15:10', '2017-03-24 13:15:10', '1', '禁用用户', '283', null);
INSERT INTO `system_resource` VALUES ('285', '禁用角色', '/system/role/disabledRole', '2', '3', '/4/10/285/', '10', '2017-03-24 13:28:47', '2017-03-24 13:28:47', '1', '禁用角色', '285', null);
INSERT INTO `system_resource` VALUES ('298', '禁用权限', '/system/resource/disabledResource', '2', '3', '/4/14/298/', '14', '2017-03-24 16:44:57', '2017-03-24 16:46:36', '1', '禁用资源', '298', null);
INSERT INTO `system_resource` VALUES ('353', '数据字典', '/dict/list', '1', '2', '/4/353', '4', '2017-04-18 09:59:45', '2017-04-18 09:59:45', '1', '数据字典', '353', null);
INSERT INTO `system_resource` VALUES ('356', '删除分组', '/dict/deleteDict', '2', '3', '/4/353/356', '353', '2017-04-19 14:09:06', '2017-04-20 14:20:25', '1', '删除分组', '356', null);
INSERT INTO `system_resource` VALUES ('357', '添加分组跳转', '/dict/toAddDict', '2', '3', '/4/353/357', '353', '2017-04-19 15:11:45', '2017-04-20 14:24:10', '1', '添加分组跳转', '357', null);
INSERT INTO `system_resource` VALUES ('358', '添加分组保存', '/dict/save', '2', '3', '/4/353/358', '353', '2017-04-19 16:12:10', '2017-04-20 14:31:32', '1', '保存分组', '358', null);
INSERT INTO `system_resource` VALUES ('359', '编辑分组跳转', '/dict/toEdit', '2', '3', '/4/353/359', '353', '2017-04-19 21:07:49', '2017-04-20 14:21:43', '1', '编辑分组跳转', '359', null);
INSERT INTO `system_resource` VALUES ('360', '分组编辑保存', '/dict/update', '2', '3', '/4/353/360', '353', '2017-04-19 21:09:12', '2017-04-26 16:29:53', '1', '分组编辑保存', '360', null);
INSERT INTO `system_resource` VALUES ('365', '添加数据跳转', '/dict/toAddDictData', '2', '3', '/4/353/365/', '353', '2017-04-20 14:23:36', '2017-04-20 14:31:52', '1', '添加组中数据', '365', null);
INSERT INTO `system_resource` VALUES ('366', '添加数据保存', '/dict/saveData', '2', '3', '/4/353/366/', '353', '2017-04-20 14:32:19', '2017-04-26 16:39:46', '1', '添加数据保存', '366', null);
INSERT INTO `system_resource` VALUES ('367', '编辑数据跳转', '/dict/toEditData', '2', '3', '/4/353/367/', '353', '2017-04-20 14:38:57', '2017-04-20 14:38:57', '1', '编辑数据跳转', '367', null);
INSERT INTO `system_resource` VALUES ('368', '数据编辑保存', '/dict/editSaveData', '2', '3', '/4/353/368/', '353', '2017-04-20 14:40:13', '2017-04-20 14:40:13', '1', '数据编辑保存', '368', null);
INSERT INTO `system_resource` VALUES ('369', '管理数据', '/dict/listData', '2', '3', '/4/353/369/', '353', '2017-04-20 14:40:35', '2017-04-20 14:41:23', '1', '管理数据', '369', null);
INSERT INTO `system_resource` VALUES ('370', '删除分组数据', '/dict/deleteDictGroup', '2', '3', '/4/353/370/', '353', '2017-04-23 14:58:47', '2017-04-23 14:59:28', '1', '删除分组数据', '370', null);
INSERT INTO `system_resource` VALUES ('371', '查询分组编码', '/dict/getGroupCodeByName', '2', '3', '/4/353/371/', '353', '2017-04-23 16:46:24', '2017-04-23 16:46:24', '1', '查询分组是否重复', '371', null);
INSERT INTO `system_resource` VALUES ('484', '改状态', '/dict/statusData', '2', '2', '/4/353/484/', '353', '2017-05-26 18:27:37', '2017-05-26 18:27:40', '1', '改状态', '484', null);
INSERT INTO `system_resource` VALUES ('518', '验证手机号', '/system/admin/validateByPhone', '2', '3', '/4/5/518/', '5', '2017-06-20 11:04:07', '2017-06-20 11:04:07', '1', '验证手机号', '518', null);
INSERT INTO `system_resource` VALUES ('531', '分配角色', '/system/role/allotRole', '2', '3', '/4/10/531/', '10', '2017-07-04 14:05:22', '2017-07-04 14:05:22', '1', '分配角色', '531', null);
INSERT INTO `system_resource` VALUES ('532', '去分配角色', '/system/role/toAllotRole', '2', '3', '/4/10/532/', '10', '2017-07-04 14:10:15', '2017-07-04 15:52:05', '1', '去分配角色', '532', null);
INSERT INTO `system_resource` VALUES ('533', '保存编辑角色', '/system/role/editRole', '2', '3', '/4/10/533/', '10', '2017-07-04 14:15:50', '2017-07-04 14:15:50', '1', '保存编辑角色', '533', null);
INSERT INTO `system_resource` VALUES ('557', '密码加密', '/system/admin/sha', '2', '3', '/4/5/557/', '5', '2018-01-15 13:21:58', '2018-01-15 13:21:58', '1', '密码加密', '557', null);
INSERT INTO `system_resource` VALUES ('558', '修改用户密码', '/system/admin/toEditPassword', '2', '3', '/4/5/558/', '5', '2018-01-17 16:43:47', '2018-01-17 17:35:38', '1', '跳转到修改用户密码页面', '558', '');
INSERT INTO `system_resource` VALUES ('559', '保存修改密码', '/system/admin/editPassword', '2', '3', '/4/5/559/', '5', '2018-01-17 17:43:30', '2018-01-17 17:43:57', '1', '保存修改密码', '559', null);
-- ----------------------------
-- Table structure for system_role
-- ----------------------------
DROP TABLE IF EXISTS `system_role`;
CREATE TABLE `system_role` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`role_name` varchar(64) NOT NULL COMMENT '角色名',
`type` varchar(2) DEFAULT NULL COMMENT '角色类型 1管理员 2普通用户',
`is_used` tinyint(10) NOT NULL COMMENT '是否使用(0,禁用,1可用)',
`create_time` datetime NOT NULL COMMENT '创建时间',
`update_time` datetime NOT NULL COMMENT '记录更新日期',
`comment` varchar(255) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8 COMMENT='系统-角色表';
-- ----------------------------
-- Records of system_role
-- ----------------------------
INSERT INTO `system_role` VALUES ('1', '超级管理员', '1', '1', '2016-06-13 10:13:45', '2017-06-15 14:15:09', null);
-- ----------------------------
-- Table structure for system_role_resource
-- ----------------------------
DROP TABLE IF EXISTS `system_role_resource`;
CREATE TABLE `system_role_resource` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`role_id` int(11) NOT NULL COMMENT '角色id',
`resource_id` int(11) NOT NULL COMMENT '资源id',
`create_time` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3246 DEFAULT CHARSET=latin1 COMMENT='角色权限表';
-- ----------------------------
-- Records of system_role_resource
-- ----------------------------
INSERT INTO `system_role_resource` VALUES ('1', '1', '1', null);
INSERT INTO `system_role_resource` VALUES ('2', '1', '2', null);
INSERT INTO `system_role_resource` VALUES ('3', '1', '3', null);
INSERT INTO `system_role_resource` VALUES ('6', '1', '10', null);
INSERT INTO `system_role_resource` VALUES ('7', '1', '14', null);
INSERT INTO `system_role_resource` VALUES ('8', '1', '24', null);
INSERT INTO `system_role_resource` VALUES ('9', '1', '25', null);
INSERT INTO `system_role_resource` VALUES ('10', '1', '181', null);
INSERT INTO `system_role_resource` VALUES ('11', '1', '165', null);
INSERT INTO `system_role_resource` VALUES ('12', '1', '166', null);
INSERT INTO `system_role_resource` VALUES ('574', '1', '274', '2017-03-31');
INSERT INTO `system_role_resource` VALUES ('575', '1', '275', '2017-03-31');
INSERT INTO `system_role_resource` VALUES ('577', '1', '285', '2017-03-31');
INSERT INTO `system_role_resource` VALUES ('580', '1', '171', '2017-03-31');
INSERT INTO `system_role_resource` VALUES ('581', '1', '172', '2017-03-31');
INSERT INTO `system_role_resource` VALUES ('582', '1', '173', '2017-03-31');
INSERT INTO `system_role_resource` VALUES ('583', '1', '298', '2017-03-31');
INSERT INTO `system_role_resource` VALUES ('584', '1', '167', '2017-03-31');
INSERT INTO `system_role_resource` VALUES ('585', '1', '168', '2017-03-31');
INSERT INTO `system_role_resource` VALUES ('586', '1', '169', '2017-03-31');
INSERT INTO `system_role_resource` VALUES ('587', '1', '170', '2017-03-31');
INSERT INTO `system_role_resource` VALUES ('619', '1', '353', '2017-04-19');
INSERT INTO `system_role_resource` VALUES ('622', '1', '356', '2017-04-19');
INSERT INTO `system_role_resource` VALUES ('623', '1', '357', '2017-04-19');
INSERT INTO `system_role_resource` VALUES ('624', '1', '358', '2017-04-19');
INSERT INTO `system_role_resource` VALUES ('625', '1', '359', '2017-04-19');
INSERT INTO `system_role_resource` VALUES ('626', '1', '360', '2017-04-19');
INSERT INTO `system_role_resource` VALUES ('631', '1', '365', '2017-04-20');
INSERT INTO `system_role_resource` VALUES ('632', '1', '366', '2017-04-20');
INSERT INTO `system_role_resource` VALUES ('633', '1', '367', '2017-04-20');
INSERT INTO `system_role_resource` VALUES ('634', '1', '368', '2017-04-20');
INSERT INTO `system_role_resource` VALUES ('635', '1', '369', '2017-04-20');
INSERT INTO `system_role_resource` VALUES ('636', '1', '370', '2017-04-20');
INSERT INTO `system_role_resource` VALUES ('637', '1', '371', '2017-04-20');
INSERT INTO `system_role_resource` VALUES ('1072', '1', '484', '2017-05-26');
INSERT INTO `system_role_resource` VALUES ('2637', '1', '531', '2017-07-04');
INSERT INTO `system_role_resource` VALUES ('2640', '1', '532', '2017-07-04');
INSERT INTO `system_role_resource` VALUES ('2641', '1', '533', '2017-07-04');
INSERT INTO `system_role_resource` VALUES ('2703', '1', '4', '2017-07-24');
INSERT INTO `system_role_resource` VALUES ('2704', '1', '5', '2017-07-24');
INSERT INTO `system_role_resource` VALUES ('2705', '1', '518', '2017-07-24');
INSERT INTO `system_role_resource` VALUES ('2706', '1', '273', '2017-07-24');
INSERT INTO `system_role_resource` VALUES ('2707', '1', '276', '2017-07-24');
INSERT INTO `system_role_resource` VALUES ('2708', '1', '283', '2017-07-24');
INSERT INTO `system_role_resource` VALUES ('2709', '1', '174', '2017-07-24');
INSERT INTO `system_role_resource` VALUES ('2710', '1', '175', '2017-07-24');
INSERT INTO `system_role_resource` VALUES ('2711', '1', '176', '2017-07-24');
INSERT INTO `system_role_resource` VALUES ('2712', '1', '238', '2017-07-24');
INSERT INTO `system_role_resource` VALUES ('3154', '1', '557', '2018-01-15');
INSERT INTO `system_role_resource` VALUES ('3164', '1', '558', '2018-01-17');
INSERT INTO `system_role_resource` VALUES ('3165', '1', '559', '2018-01-17');
|
------ Tambahan Soal----------------
1. Buatlah query untuk menampilkan jumlah transaksi terbesar !
2. Buatlah query untuk menampilkan jumlah transaksi terkecil!
3. Buatlah query untuk menampilkan menampilkan nasabah dengan jumlah transaksi terbesar!
4. Buatlah query untuk menampilkan cabang bank yang tidak memiliki nomor rekening !
5. Buatlah query untuk menampilkan nomor rekening dengan saldo diatas rata-rata !
select nama_kolom
from nama_table
where (select nama_kolom from nama_table where kondisi);
update nama_table
set nama_kolom = (select nama_kolom from nama_table where kondisi)
where nama_kolom = (select nama_kolom from nama_table where kondisi);
delete from nama_table
where (select nama_kolom from nama_table where kondisi);
-----Menampilkan data dari table transaksi yang jumlahnya lebih dari rata-rata jumlah----
select *
from transaksi
where jumlah > (select avg(jumlah) from transaksi); |
INSERT INTO table1 (id,name,email) VALUES (1, 'a','xxxx@mail.co.jp');
INSERT INTO table1 (id,name,email) VALUES (2, 'b','xxxx@mail.co.jp');
INSERT INTO table1 (id,name,email) VALUES (3, 'c','xxxx@mail.co.jp');
INSERT INTO table1 (id,name,email) VALUES (4, 'd','xxxx@mail.co.jp');
INSERT INTO table2 (id,val,email) VALUES (1, 'A','xxxx@mail.co.jp');
INSERT INTO table2 (id,val,email) VALUES (10, 'AA','xxxx@mail.co.jp'); |
insert into body(name)
values
('sedan'),('Hatchback'),('Coupe'),('Van'),('jeep');
insert into engine(name)
values
('v8'),('v4'),('v2');
insert into transmission(name)
values
('auto'),('mechanical');
insert into cars(name,body_id,engine_id,transmission_id)
values
('Toyota 4runner',5,1,1),
('Lexus 570LX',5,1,1),
('Audi A8',1,1,1),
('Audi A6',1,2,1); |
-- 1. 查询出只选修了一门课程的全部学生的学号和姓名
-- 都选修了至少两门课啊
SELECT student.sname,student.sid FROM student,sc GROUP BY student.sid HAVING NOT COUNT(sc.sid)>1;
-- 2. 查询不同课程成绩相同的学生的学号、课程号、学生成绩
SELECT DISTINCT
a.sid,
a.score,
a.cid
FROM
sc AS a
INNER JOIN sc AS b ON a.sid = b.sid
WHERE
a.score = b.score
AND a.cid != b.cid;
-- 3. 查询平均成绩大于70 的所有学生的学号、姓名和平均成绩
SELECT sc.sid,student.sname,SUM(sc.score)/COUNT(sc.score) AS avgs FROM sc,student WHERE student.sid=sc.sid GROUP BY sid;
-- 4. 查询所有学生的选课情况
SELECT sc.sid,student.sname,course.cid,course.cname FROM sc,student,course WHERE student.sid=sc.sid AND course.cid=sc.cid;
-- 5. 查询课程名称为“数据库”,且分数低于60的学生姓名和分数;
SELECT student.sid,student.sname FROM sc,student,course WHERE course.cid=sc.cid AND sc.sid=student.sid AND sc.score<60;
-- 6. 查询任何一门课程成绩在70分以上的姓名、课程名称和分数
SELECT student.sname,course.cname,sc.score FROM student,sc,course WHERE course.cid=sc.cid AND sc.sid=student.sid AND sc.score>70;
SELECT student.sname,course.cname,sc.score FROM course INNER JOIN sc ON course.cid=sc.cid INNER JOIN student ON sc.sid=student.sid AND sc.score>70;
-- 7. 查询有不及格的课程的课程编号,课程名称,成绩,并按课程号从大到小排列
SELECT course.cid,course.cname,sc.score FROM course INNER JOIN sc ON sc.cid=course.cid AND sc.score<60 GROUP BY sc.score DESC;
-- 8. 查询选了课程编号为003且课程成绩在70分以上的学生的学号和姓名
SELECT student.sid,student.sname from sc,student where student.sid=sc.sid AND sc.cid='003' AND sc.score>70;
-- 9. 查询选修“叶平”老师所授课程的学生中,成绩最高的学生姓名及其成绩
-- 10. 查询没学过“叶平”老师讲授的任一门课程的学生姓名
-- 11. 查询两门以上不及格课程的同学的学号及其平均成绩
SELECT sid,avg(score),COUNT(*) from sc WHERE score<60 GROUP BY sid HAVING COUNT(*)>2;
|
DO
$BODY$
DECLARE
hypertable_name TEXT;
BEGIN
SELECT first_dim.schema_name || '.' || first_dim.table_name
FROM _timescaledb_catalog.continuous_agg ca
INNER JOIN LATERAL (
SELECT dim.*, h.*
FROM _timescaledb_catalog.hypertable h
INNER JOIN _timescaledb_catalog.dimension dim ON (dim.hypertable_id = h.id)
WHERE ca.raw_hypertable_id = h.id
ORDER by dim.id ASC
LIMIT 1
) first_dim ON true
WHERE first_dim.column_type IN (REGTYPE 'int2', REGTYPE 'int4', REGTYPE 'int8')
AND (first_dim.integer_now_func_schema IS NULL OR first_dim.integer_now_func IS NULL)
INTO hypertable_name;
IF hypertable_name is not null AND (current_setting('timescaledb.ignore_update_errors', true) is null OR current_setting('timescaledb.ignore_update_errors', true) != 'on') THEN
RAISE 'The continuous aggregate on hypertable "%" will break unless an integer_now func is set using set_integer_now_func().', hypertable_name;
END IF;
END
$BODY$;
ALTER TABLE _timescaledb_catalog.continuous_agg
ADD COLUMN ignore_invalidation_older_than BIGINT NOT NULL DEFAULT BIGINT '9223372036854775807';
UPDATE _timescaledb_catalog.continuous_agg SET ignore_invalidation_older_than = BIGINT '9223372036854775807';
CLUSTER _timescaledb_catalog.continuous_agg USING continuous_agg_pkey;
ALTER TABLE _timescaledb_catalog.continuous_agg SET WITHOUT CLUSTER;
CREATE INDEX IF NOT EXISTS continuous_agg_raw_hypertable_id_idx
ON _timescaledb_catalog.continuous_agg(raw_hypertable_id);
--Add modification_time column
CREATE TABLE _timescaledb_catalog.continuous_aggs_hypertable_invalidation_log_tmp AS SELECT * FROM _timescaledb_catalog.continuous_aggs_hypertable_invalidation_log;
ALTER EXTENSION timescaledb DROP TABLE _timescaledb_catalog.continuous_aggs_hypertable_invalidation_log;
DROP TABLE _timescaledb_catalog.continuous_aggs_hypertable_invalidation_log;
CREATE TABLE IF NOT EXISTS _timescaledb_catalog.continuous_aggs_hypertable_invalidation_log
(
hypertable_id INTEGER NOT NULL,
modification_time BIGINT NOT NULL, --time at which the raw table was modified
lowest_modified_value BIGINT NOT NULL,
greatest_modified_value BIGINT NOT NULL
);
SELECT pg_catalog.pg_extension_config_dump('_timescaledb_catalog.continuous_aggs_hypertable_invalidation_log', '');
--modification_time == INT_MIN to cause these invalidations to be processed
INSERT INTO _timescaledb_catalog.continuous_aggs_hypertable_invalidation_log
SELECT hypertable_id, BIGINT '-9223372036854775808', lowest_modified_value, greatest_modified_value
FROM _timescaledb_catalog.continuous_aggs_hypertable_invalidation_log_tmp;
DROP TABLE _timescaledb_catalog.continuous_aggs_hypertable_invalidation_log_tmp;
CREATE INDEX continuous_aggs_hypertable_invalidation_log_idx
ON _timescaledb_catalog.continuous_aggs_hypertable_invalidation_log (hypertable_id, lowest_modified_value ASC);
GRANT SELECT ON _timescaledb_catalog.continuous_aggs_hypertable_invalidation_log TO PUBLIC;
--Add modification_time column
CREATE TABLE _timescaledb_catalog.continuous_aggs_materialization_invalidation_log_tmp AS SELECT * FROM _timescaledb_catalog.continuous_aggs_materialization_invalidation_log;
ALTER EXTENSION timescaledb DROP TABLE _timescaledb_catalog.continuous_aggs_materialization_invalidation_log;
DROP TABLE _timescaledb_catalog.continuous_aggs_materialization_invalidation_log;
CREATE TABLE IF NOT EXISTS _timescaledb_catalog.continuous_aggs_materialization_invalidation_log
(
materialization_id INTEGER
REFERENCES _timescaledb_catalog.continuous_agg (mat_hypertable_id)
ON DELETE CASCADE,
modification_time BIGINT NOT NULL, --time at which the raw table was modified
lowest_modified_value BIGINT NOT NULL,
greatest_modified_value BIGINT NOT NULL
);
SELECT pg_catalog.pg_extension_config_dump('_timescaledb_catalog.continuous_aggs_materialization_invalidation_log', '');
--modification_time == INT_MIN to cause these invalidations to be processed
INSERT INTO _timescaledb_catalog.continuous_aggs_materialization_invalidation_log
SELECT materialization_id, BIGINT '-9223372036854775808', lowest_modified_value, greatest_modified_value
FROM _timescaledb_catalog.continuous_aggs_materialization_invalidation_log_tmp;
DROP TABLE _timescaledb_catalog.continuous_aggs_materialization_invalidation_log_tmp;
CREATE INDEX continuous_aggs_materialization_invalidation_log_idx
ON _timescaledb_catalog.continuous_aggs_materialization_invalidation_log (materialization_id, lowest_modified_value ASC);
GRANT SELECT ON _timescaledb_catalog.continuous_aggs_materialization_invalidation_log TO PUBLIC;
ALTER TABLE _timescaledb_config.bgw_policy_drop_chunks ALTER COLUMN cascade_to_materializations DROP NOT NULL;
UPDATE _timescaledb_config.bgw_policy_drop_chunks SET cascade_to_materializations = NULL WHERE cascade_to_materializations = false;
ALTER TABLE _timescaledb_catalog.chunk ADD COLUMN dropped BOOLEAN DEFAULT false;
UPDATE _timescaledb_catalog.chunk SET dropped = false;
ALTER TABLE _timescaledb_catalog.chunk ALTER COLUMN dropped SET NOT NULL;
CLUSTER _timescaledb_catalog.chunk USING chunk_pkey;
ALTER TABLE _timescaledb_catalog.chunk SET WITHOUT CLUSTER;
|
CREATE PROC [ERP].[Usp_Upd_Chofer_Desactivar]
@IdChofer INT
AS
BEGIN
UPDATE ERP.Chofer SET Flag = 0 , FechaEliminado = DATEADD(HOUR, 3, GETDATE()) WHERE ID = @IdChofer
END
|
create PROC [ERP].[Usp_Sel_Parametro_By_Abreviatura]
@Abreviatura VARCHAR(5)
AS
BEGIN
SELECT PA.ID ID,
PE.ID IdPeriodo,
TPA.ID IdTipoParametro,
PA.Nombre NombreParametro,
PA.Abreviatura Abreviatura,
PA.Valor Valor,
TPA.Nombre NombreTipoParametro,
PE.IdAnio IdAnio,
PE.IdMes IdMes,
PA.UsuarioRegistro,
PA.UsuarioModifico,
PA.FechaRegistro,
PA.FechaModificado
FROM [ERP].[Parametro] PA
INNER JOIN [ERP].[Periodo] PE
ON PE.ID=PA.IdPeriodo
INNER JOIN [Maestro].[TipoParametro] TPA
ON TPA.ID=PA.IdTipoParametro
WHERE PA.Abreviatura = @Abreviatura
END
|
16 Atributos:
Campañas (Status): Activa, Inactiva, Finalizada
Clientes (Status): Ninguno, Potencial, Actual
Clientes (StatusActual): Activo, Inactivo
Clientes (Edad): Niño, Joven, Adulto, Anciano
Clientes (Genero): Hombre, Mujer
Clientes (Educación): Ninguna, Primaria, Secundaria, Preparatoria o Bachillerato, Licenciatura, Maestria o Doctorado
Clientes (Ocupación): Estudiante, Labores del hogar, Profesionales por cuenta ajena, Profesionales por cuenta propia, Desempleado, Directivo, Cargos Intermedios, Otros
Clientes (Estado civil): Soltero, Unión Libre, Casado, Divorciado, Viudo
Clientes (Clase social): Baja, Media, Alta
Emails (Status): Enviado, En espera, Leido
Clientes (Tendencia): Primavera, Verano, Otoño, Invierno
Clientes (Ocasión de compra): Ocasión ordinaria, Ocasión especial
Mercados (Status): Objetivo, Activo, Inactivo
Usuarios (Roles): Administrador, Jefe de Marketing, Promotor, Vendedor
Espacio de búsqueda
(3 x 2 x 4 x 2 x 6 x 8 x 5 x 5 x 3 x 3 x 7 x 9 x 4 x 2 x 3 x 4) = 3,135,283,200
Ejemplo
Reglas (Lista de decisiones)
Si Usuario.Rol = Administrador o Usuario.Rol = Jefe de Marketing y Mercado.Objetivo Entonces Crear.Camapaña
--Potenciales o actuales
Si Cliente.Edad = Joven y (Cliente.Genero = Hombre o Cliente.Genero = Mujer) y Cliente.Escuela = Licenciatura y Cliente.Ocupacion = Estudiante y Cliente.Estado_Civil = Soltero y Cliente.Clase_Social = Media y Cliente.Status = Ninguno Entonces Cliente.Status = Potencial
--Estatus del cliente
Si Cliente.Status = Actual y Cliente.Compras > 0 Entonces Cliente.StatusActual = Activo
--Edad Cliente (Niño, Joven, Adulto Joven, Alduto Maduro, Anciano)
Clientes.Birthday (Fecha_nacimiento)
If Cliente.Edad >= 0 AND Cliente.Edad < 12 Then Cliente.Cliente = Niño(a)
If Cliente.Edad >= 12 AND Cliente.Edad < 18 Then Cliente.Cliente = Joven
If Cliente.Edad >= 18 AND Cliente.Edad < 35 Then Cliente.Cliente = Adulto Joven
If Cliente.Edad >= 35 AND Cliente.Edad < 59 Then Cliente.Cliente = Adulto Maduro
If Cliente >= 60 Then Cliente.Cliente = Anciano
0 a 11 -> Niños (as)
12 a 17 -> Jovenes
18 a 34 -> Adulto Joven
35 a 59 -> Adulto Maduro
60 -> Ancianos (as)
--Ingresos por tamaño de familia, y estado civil
--Clase Social se determina por:
-- Ocupación, Educación, Familia, Estado_Civil Ingresos
If (Cliente.Ocupacion = Desempleado OR Cliente.Ocupacion = Otros OR Cliente.Ocupacion = Labores del hogar) AND (Cliente.Educación = Niguna OR Cliente.Educación = Primaria o Cliente.Educación = Secundaria) Then Cliente.Clase_Social = Baja
If (Cliente.Ocupacion = Cargos Intermedios OR Cliente.Ocupacion = Profesionales por cuenta propia OR Cliente.Ocupacion = Profesionales por cuenta ajena) AND (Cliente.Educación = Primaria OR Cliente.Educación = Preparatoria o Bachillerato Cliente.Educación.Licenciatura OR Cliente.Educación = Doctorado o Maestria) Then = Cliente.Clase_Social = Media
If Cliente.Ocupacion = Directivo AND (Cliente.Educación = Licenciatura OR Cliente.Educación = Maestria o Doctorado) Then Cliente.Clase_Social = Alta
--Campañas (Activa, Inactiva, Finalizada)
If Campañas.Date_Start <= Campañas.Now AND Campañas.Date_End >= Campañas.Now Then Campañas.Status = Activa
If Campañas.Date_Start > Campañas.Now Then Campañas.Status = Inactiva
If Campañas.Date_End < Campañas.Now Then Campañas.Status = Finalizada
foreign key (table_name_id) references table_names(id),
|
CREATE TABLE IF NOT EXISTS "sym_node"(
"node_id" VARCHAR NOT NULL PRIMARY KEY ,
"node_group_id" VARCHAR NOT NULL,
"external_id" VARCHAR NOT NULL,
"sync_enabled" INTEGER DEFAULT 0,
"sync_url" VARCHAR,
"schema_version" VARCHAR,
"symmetric_version" VARCHAR,
"database_type" VARCHAR,
"database_version" VARCHAR,
"heartbeat_time" TIMESTAMP,
"timezone_offset" VARCHAR,
"batch_to_send_count" INTEGER DEFAULT 0,
"batch_in_error_count" INTEGER DEFAULT 0,
"created_at_node_id" VARCHAR,
"deployment_type" VARCHAR
);
CREATE TABLE IF NOT EXISTS "sym_node_identity"(
"node_id" VARCHAR NOT NULL PRIMARY KEY ,
FOREIGN KEY ("node_id") REFERENCES "sym_node" ("node_id")
);
insert into sym_node (node_id,node_group_id,external_id,sync_enabled,sync_url,schema_version,symmetric_version,database_type,database_version,heartbeat_time,timezone_offset,batch_to_send_count,batch_in_error_count,created_at_node_id)
values ('002','store','002',1,null,null,null,null,null,current_timestamp,null,0,0,'000');
INSERT INTO "sym_node_identity" VALUES('002');
|
CREATE TABLE persons
(
first_name VARCHAR(255),
second_name CHAR(1)
);
INSERT INTO persons
VALUES ('Mykyta', 'Kostiuk');
ALTER TABLE persons
CHANGE second_name second_name varchar(255);
SELECT *
FROM persons;
select concat(first_name, ' ', second_name) as full_name
from persons;
#Customer, Drink_order
DROP TABLE CUSTOMERS;
DROP TABLE DRINK_ORDERS;
CREATE TABLE CUSTOMERS
(
ID INTEGER PRIMARY KEY,
FIRST_NAME VARCHAR(255),
LAST_NAME VARCHAR(255),
ADDRESS VARCHAR(255),
STATE VARCHAR(2),
ZIP_CODE int(5)
);
CREATE TABLE DRINK_ORDERS
(
ID INTEGER PRIMARY KEY,
CUSTOMER_ID INTEGER,
DRINK_DESCRIPTION CHAR(255),
CONSTRAINT DRINK_ORDERS_CUSTOMERS_FK
FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMERS (ID)
);
INSERT INTO CUSTOMERS
VALUES (1234, 'Michael', 'Weston', '123 Brickel', 'FL', 33135);
SELECT *
FROM CUSTOMERS;
INSERT INTO DRINK_ORDERS
VALUES (12341234, 1234, 'Scotch');
SELECT *
FROM DRINK_ORDERS;
#
|
CREATE INDEX created_date_index ON public.employee (created_date);
|
-- Mathew Varughese MAV120
-- 2
DROP TABLE CUSTOMERS cascade constraints;
DROP TABLE RECORDS cascade constraints;
DROP TABLE STATEMENTS cascade constraints;
DROP TABLE PAYMENTS cascade constraints;
DROP TABLE DIRECTORY cascade constraints;
CREATE TABLE DIRECTORY(
pn NUMBER(10),
fname VARCHAR2(20),
lname VARCHAR2(20),
street VARCHAR2(20),
city VARCHAR2(20),
zip NUMBER(5),
state VARCHAR2(20),
CONSTRAINT PK_Directory PRIMARY KEY(pn)
);
CREATE TABLE CUSTOMERS(
SSN NUMBER(9),
fname VARCHAR2(20) NOT NULL,
lname VARCHAR2(20) NOT NULL,
cell_pn NUMBER(10),
home_pn NUMBER(10),
street VARCHAR2(20),
city VARCHAR2(20),
zip NUMBER(5),
state VARCHAR2(20),
free_min NUMBER,
dob DATE,
CONSTRAINT PK_Customers PRIMARY KEY(SSN),
CONSTRAINT FK_Customers_cell_pn FOREIGN KEY(cell_pn) references DIRECTORY(pn),
CONSTRAINT FK_Customers_home_pn FOREIGN KEY(home_pn) references DIRECTORY(pn)
);
CREATE TABLE RECORDS(
from_pn NUMBER(10),
to_pn NUMBER(10),
start_timestamp TIMESTAMP,
duration NUMBER(4),
type VARCHAR2(20) CHECK (type IN ('call', 'sms')),
CONSTRAINT PK_Records PRIMARY KEY(from_pn, to_pn, start_timestamp, type),
CONSTRAINT FK_Records_from_pn FOREIGN KEY(to_pn) references DIRECTORY(pn),
CONSTRAINT FK_Records_to_pn FOREIGN KEY(from_pn) references DIRECTORY(pn)
);
CREATE TABLE STATEMENTS(
cell_pn NUMBER(10),
start_date DATE,
end_date DATE,
total_minutes NUMBER,
total_SMS NUMBER,
amount_due NUMBER(6, 2),
CONSTRAINT PK_Statements PRIMARY KEY(cell_pn, start_date, end_date)
);
CREATE TABLE PAYMENTS(
cell_pn NUMBER(10),
paid_on TIMESTAMP,
amount_paid NUMBER(6, 2),
CONSTRAINT PK_Payments PRIMARY KEY(cell_pn, paid_on, amount_paid)
);
-- 3a
ALTER TABLE CUSTOMERS ADD CONSTRAINT customer_Uniq_Cell_Pn UNIQUE (cell_pn);
-- 3b
ALTER TABLE CUSTOMERS ADD free_SMS NUMBER;
-- 3c
ALTER TABLE STATEMENTS ADD previous_balance NUMBER(6, 2);
-- 3d
ALTER TABLE CUSTOMERS MODIFY free_min DEFAULT 0;
ALTER TABLE CUSTOMERS MODIFY free_SMS DEFAULT 0; |
-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: May 08, 2017 at 01:38 PM
-- Server version: 10.1.22-MariaDB
-- PHP Version: 5.6.30
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: `lalbus_db`
--
-- --------------------------------------------------------
--
-- Table structure for table `bus`
--
CREATE TABLE `bus` (
`id` int(11) NOT NULL,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`route` varchar(50) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `bus`
--
INSERT INTO `bus` (`id`, `name`, `route`) VALUES
(1, 'Choitali', 'মিরপুর-১২'),
(2, 'Boishakhi', 'কচুক্ষেত'),
(3, 'Taranga', 'মোহাম্মদপুর / জাপান গার্ডেন'),
(4, 'Khonika', 'টঙ্গী/গাজীপুর'),
(5, 'Srabon', 'মুগদাপাড়া'),
(6, 'Isha Kha', 'মেঘনা ঘাট'),
(7, 'Falguni', 'বাড্ডা / গুলশান'),
(8, 'Hemonto', 'নবীনগর (সাভার)'),
(9, 'Ullash', 'পোস্তগোলা'),
(10, 'Anando', 'নারায়ণগঞ্জ'),
(11, 'Moitri', 'আদমজী আইটি স্কুল'),
(12, 'Kinchit', 'কমলাপুর'),
(13, 'Boshonto', 'রামপুরা '),
(14, 'Uwari', 'নরসিংদী / ইটাখোলা');
-- --------------------------------------------------------
--
-- Table structure for table `bus_request`
--
CREATE TABLE `bus_request` (
`id` int(11) NOT NULL,
`update_type` int(11) NOT NULL DEFAULT '0',
`old_id` int(11) NOT NULL,
`name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
`route` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
`remarks` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(11) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `bus_request`
--
INSERT INTO `bus_request` (`id`, `update_type`, `old_id`, `name`, `route`, `remarks`, `user_id`, `timestamp`) VALUES
(1, 0, 1, 'Choitali', 'মিরপুর-১২', '', 1, '2017-05-07 16:12:50');
-- --------------------------------------------------------
--
-- Table structure for table `depts`
--
CREATE TABLE `depts` (
`id` int(11) NOT NULL,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`short_name` varchar(20) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `depts`
--
INSERT INTO `depts` (`id`, `name`, `short_name`) VALUES
(1, 'Department of Bengali', 'BNG'),
(2, 'Department of English', 'ENG'),
(3, 'Department of Arabic', 'ARB'),
(4, 'Department of Persian Language and Literature', 'PERS'),
(5, 'Department of Urdu', 'UPS'),
(6, 'Department of Sanskrit', 'SPL'),
(7, 'Department of Pali and Buddhist Studies', 'PBS'),
(8, 'Department of History', 'HIS'),
(9, 'Department of Philosophy', 'PHI'),
(10, 'Department of Islamic Studies', 'IST'),
(11, 'Department of Islamic History & Culture', 'IHC'),
(12, 'Department of Information Science and Library Management', 'LIS'),
(13, 'Department of Theatre and Performance Studies', 'TMU'),
(14, 'Department of Linguistics', 'LIN'),
(15, 'Department of Music', 'DMUSIC'),
(16, 'Department of World Religions and Culture', 'WRC'),
(17, 'Department of Dance', 'DDANCE'),
(18, 'Department of Physics', 'PHY'),
(19, 'Department of Mathematics', 'MAT'),
(20, 'Department of Chemistry', 'CHM'),
(21, 'Department of Statistics', 'STA'),
(22, 'Department of Theoretical Physics', 'TPHY'),
(23, 'Department of Biomedical Physics & Technology', 'BIOPHY'),
(24, 'Department of Applied Mathematics', 'APMAT'),
(25, 'Department of Law', 'LAW'),
(26, 'Department of Management', 'MAN'),
(27, 'Department of Accounting & Information Systems', 'AIS'),
(28, 'Department of Marketing', 'MRK'),
(29, 'Department of Finance', 'FIN'),
(30, 'Department of Banking and Insurance', 'BAN'),
(31, 'Department of Management Information Systems (MIS)', 'MIS'),
(32, 'Department of International Business', 'INTBS'),
(33, 'Department of Tourism and Hospitality Management', 'BSTHM'),
(34, 'Department of Organization Strategy and Leadership', 'OSL'),
(35, 'Department of Soil, Water & Environment', 'SWE'),
(36, 'Department of Botany', 'BOT'),
(37, 'Department of Zoology', 'ZOO'),
(38, 'Department of Biochemistry and Molecular Biology', 'BMB'),
(39, 'Department of Psychology', 'PSY'),
(40, 'Department of Microbiology', 'MBI'),
(41, 'Department of Fisheries', 'AQF'),
(42, 'Department of Clinical Psychology', 'CPS'),
(43, 'Department of Genetic Engineering and Bio-Technology', 'GEB'),
(44, 'Department of Educational and Counselling Psychology', 'ECP'),
(45, 'Department of Economics', 'ECO'),
(46, 'Department of Political Science', 'PSC'),
(47, 'Department of International Relations', 'IRL'),
(48, 'Department of Sociology', 'SOC'),
(49, 'Department of Mass Communication & Journalism', 'MCJ'),
(50, 'Department of Public Administration', 'PUB'),
(51, 'Department of Anthropology', 'ANT'),
(52, 'Department of Population Sciences', 'POPS'),
(53, 'Department of Peace and Conflict Studies', 'PCE'),
(54, 'Department of Women and Gender Studies', 'WGS'),
(55, 'Department of Development Studies', 'DVS'),
(56, 'Department of Television, Film and Photography', 'TFP'),
(57, 'Department of Criminology', 'CLG'),
(58, 'Department of Communication Disorders', 'COMD'),
(59, 'Department of Printing and Publication Studies', 'DPUB'),
(60, 'Department of Pharmaceutical Chemistry', 'PHCM'),
(61, 'Department of Clinical Pharmacy and Pharmacology', 'CPP'),
(62, 'Department of Pharmaceutical Technology', 'PTCH'),
(63, 'Department of Pharmacy', 'PHAR'),
(64, 'Department of Geography & Environment', 'GEN'),
(65, 'Department of Geology', 'GLG'),
(66, 'Department of Oceanography', 'OCG'),
(67, 'Department of Disaster Science and Management', 'DSM'),
(68, 'Department of Meteorology', 'DEMET'),
(69, 'Department of Electrical and Electronic Engineering', 'EEE'),
(70, 'Department of Applied Chemistry & Chemical Engineering', 'ACCE'),
(71, 'Department of Computer Science and Engineering', 'CSE'),
(72, 'Department of Nuclear Engineering', 'NE'),
(73, 'Department of Robotics and Mechatronics Engineering', 'RME'),
(74, 'Department of Drawing and Painting', 'DDP'),
(75, 'department of graphic design', 'GDESIGN'),
(76, 'Department of Printmaking', 'DPMK'),
(77, 'Department of Oriental Art', 'OARTS'),
(78, 'Department of Ceramics', 'DCER'),
(79, 'Department of Sculpture', 'DSCULP'),
(80, 'Department of Craft', 'DCRAFT'),
(81, 'Department of History of Arts', 'HIARTS'),
(82, 'Institute of Statistical Research and Training', 'ISRT'),
(83, 'Institute of Education and Research', 'IER'),
(84, 'Institute of Business Administration', 'IBA'),
(85, 'Institute of Nutrition and Food Science', 'INFS'),
(86, 'Institute of Social Welfare and Research', 'ISWR'),
(87, 'Institute of Modern Languages', 'IML'),
(88, 'Institute of Information Technology', 'IIT'),
(89, 'Institute of Renewable Energy', 'IRE'),
(90, 'Institute of Disaster Management and Vulnerability Studies', 'IDMV'),
(91, 'Institute of Leather Engineering & Technology', 'ILET'),
(92, 'Institute of Health Economics', 'IHE'),
(93, 'Confucius Institute', 'CIST');
-- --------------------------------------------------------
--
-- Table structure for table `following`
--
CREATE TABLE `following` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `following`
--
INSERT INTO `following` (`id`, `user_id`, `bus_id`) VALUES
(1, 1, 1),
(2, 2, 2),
(3, 21, 4),
(4, 3, 1),
(5, 4, 12),
(8, 22, 2),
(9, 22, 2),
(10, 5, 7),
(11, 5, 2),
(12, 5, 0),
(13, 5, 4),
(14, 5, 5),
(15, 5, 6),
(16, 6, 6),
(17, 7, 2),
(18, 8, 12),
(22, 10, 7),
(24, 9, 2),
(25, 11, 4),
(26, 12, 5),
(27, 13, 5),
(28, 13, 1),
(29, 13, 2),
(30, 13, 3),
(31, 13, 4),
(32, 13, 6),
(33, 13, 7),
(34, 13, 8),
(35, 13, 9);
-- --------------------------------------------------------
--
-- Table structure for table `places`
--
CREATE TABLE `places` (
`id` int(11) NOT NULL,
`stoppage_name` varchar(600) NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`bus_id` int(11) NOT NULL,
`stoppage_type` int(11) NOT NULL,
`remarks` varchar(600) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `places`
--
INSERT INTO `places` (`id`, `stoppage_name`, `lat`, `lng`, `bus_id`, `stoppage_type`, `remarks`) VALUES
(1, 'Mirpur-1', 23.795604, 90.353655, 1, 2, ''),
(2, 'Mirpur-2', 23.797675, 90.3845, 1, 2, ''),
(3, 'Setara Convention Hall, Begum Rokeya Avenue, Dhaka, Bangladesh', 23.822524, 90.364233, 1, 2, ''),
(4, 'Digilab Diagnostic Center, Mirpur, Dhaka, Bangladesh', 23.821176, 90.364963, 1, 2, ''),
(5, 'Rabbani Hotel and Restaurant, Mirpur Road, Dhaka, Bangladesh', 23.81574, 90.366251, 1, 2, ''),
(6, 'Original 10, Dhaka, Dhaka Division, Bangladesh', 23.81037, 90.367522, 1, 2, ''),
(7, 'Proshika More Bus Stop, Dhaka, Bangladesh', 23.809472, 90.360999, 1, 2, ''),
(8, 'Janata housing, Mirpur-1, Dhaka, Dhaka Division, Bangladesh', 23.798939, 90.358655, 1, 2, ''),
(9, 'Ansar Camp Road, Mirpur, Dhaka, Bangladesh', 23.791159, 90.354722, 1, 2, ''),
(10, 'Bangla College, Dhaka, Dhaka Division, Bangladesh', 23.784822, 90.352773, 1, 2, ''),
(11, 'Kallyanpur, Mirpur, Dhaka, Dhaka Division, Bangladesh', 23.782204, 90.359537, 1, 2, ''),
(12, 'Kalyanpur', 23.782204, 90.359537, 1, 2, ''),
(13, 'Shyamoli, Dhaka, Dhaka Division, Bangladesh', 23.771783, 90.363067, 1, 2, ''),
(14, 'Kachukhet Bus Stop, Kachukhet Road, Dhaka, Bangladesh', 23.792862, 90.388043, 2, 2, ''),
(15, 'Mirpur 14 Bus Stand, Kachukhet Road, Dhaka, Bangladesh', 23.798269, 90.387561, 2, 2, ''),
(16, 'Shaheed police smrity college,Police Complex, Mirpur-14, Dhaka 1206, Bangladesh', 23.799965, 90.384936, 2, 2, ''),
(17, 'Police Staff College,14 Mirpur Rd, Dhaka 1206, Bangladesh', 23.802712, 90.380262, 2, 2, ''),
(18, 'Mirpur-13', 23.807393, 90.378485, 2, 2, ''),
(19, 'Mirpur-10 Water Tank', 23.806796, 90.373566, 2, 2, ''),
(20, 'Mirpur 10 Bus Stopage, Dhaka, Bangladesh', 23.806744, 90.368555, 2, 2, ''),
(21, 'Kazipara Overpass, Dhaka, Bangladesh', 23.797165, 90.372993, 2, 2, ''),
(22, 'ShewraPara Bus Stand, Begum Rokeya Ave, Dhaka 1216, Bangladesh', 23.790398, 90.375568, 2, 2, ''),
(23, 'Taltola, Begum Rokeya Ave, Dhaka 1207, Bangladesh', 23.783516, 90.378483, 2, 2, ''),
(24, 'Sher E Bangla Agricultural University', 23.77123, 90.375225, 2, 2, ''),
(25, 'Residential School', 23.765836, 90.3699, 3, 2, ''),
(26, 'DRMC', 23.765836, 90.3699, 3, 2, ''),
(27, 'Lalmatia, Dhaka, Bangladesh', 23.755407, 90.368951, 3, 2, ''),
(28, 'State University of Bangladesh,77 Satmasjid Road, Dhaka 1205, Bangladesh', 23.751436, 90.367424, 3, 2, ''),
(29, 'Dhanmondi 15, Dhaka 1209, Bangladesh', 23.747463, 90.370273, 3, 2, ''),
(30, 'Zigatola Bus stop,Dhaka, Bangladesh', 23.738528, 90.376074, 3, 2, ''),
(31, 'Star Kabab,9/A Dhanmondi Lake Rd,Dhanmondi 15 Dhaka, Bangladesh', 23.747463, 90.370273, 3, 2, ''),
(32, 'Sankar Bus Stop, Satmasjid Road, Dhaka 1209, Bangladesh', 23.750748, 90.368419, 3, 2, ''),
(33, 'Lalmatia, Dhaka, Bangladesh', 23.755407, 90.368951, 3, 2, ''),
(34, 'City Hospital Ltd, Lalmatia', 23.754067, 90.365531, 3, 2, ''),
(35, 'Nurjahan Rd, Dhaka 1209, Bangladesh', 23.76043, 90.361774, 3, 2, ''),
(36, 'Mugdapara Bus Stop, Atish Deepankar Rd, Dhaka, Bangladesh', 23.73119, 90.428569, 5, 2, ''),
(37, 'Bashabo, Dhaka, Bangladesh', 23.742604, 90.430784, 5, 2, ''),
(38, 'Khilgaon Railgate Staff Quarter Jame Masjid', 23.743767, 90.426865, 5, 2, ''),
(39, 'Maniknagar, Dhaka, Bangladesh', 23.724744, 90.43432, 5, 2, ''),
(40, 'Kazla Bus Stop, Dhaka-Chittagong Highway (Mukti Sharani), Dhaka, Bangladesh', 23.705691, 90.444072, 6, 2, ''),
(41, 'Shonir Akhra Bus Stop, Dhaka, Bangladesh', 23.702913, 90.450395, 6, 2, ''),
(42, 'Rayerbag Bus Stop, Dhaka, Bangladesh', 23.699351, 90.457106, 6, 2, ''),
(43, 'Matuail Medi Care Hospital & Diagnostic Center', 23.713089, 90.469681, 6, 2, ''),
(44, 'Saddam Market Bus Stop, Tushar Dhara Ave New Rd, Dhaka, Bangladesh', 23.692969, 90.472957, 6, 2, ''),
(45, 'Sign Board Bus Stop, Dhaka - Narayanganj Rd, Dhaka, Bangladesh', 23.693685, 90.480834, 6, 2, ''),
(46, 'Sanarpar Bus Stop, Bangladesh', 23.694756, 90.490233, 6, 2, ''),
(47, 'Mouchak Rd, Dhaka, Bangladesh', 23.688806, 90.496899, 6, 2, ''),
(48, 'Chittagong Road Bus Stop, Shiddhirganj, Bangladesh', 23.697853, 90.509706, 6, 2, ''),
(49, 'Kanchpur Bus Stop, N1, Bangladesh', 23.706083, 90.522011, 6, 2, ''),
(50, 'Kachpur Bus Stop, N1, Bangladesh', 23.706083, 90.522011, 6, 2, ''),
(51, 'Modonpur Bus Stop, Bandar, Bangladesh', 23.690578, 90.546538, 6, 2, ''),
(52, 'Sonargaon, Bangladesh', 23.63661, 90.594665, 6, 2, ''),
(53, 'Meghna Ghat Bus Stop, Bangladesh', 23.61841, 90.609353, 6, 2, ''),
(54, 'Natun Bazaar Bus Stand, Dhaka, Bangladesh', 23.797383, 90.42371, 7, 2, ''),
(55, 'Bashtola Bus Stand, Baash Tola Rd, Dhaka, Bangladesh', 23.794514, 90.4241, 7, 2, ''),
(56, 'Shahjadpur, Dhaka, Bangladesh', 23.791707, 90.424891, 7, 2, ''),
(57, 'suvastu nazar valley', 23.789814, 90.425198, 7, 2, ''),
(58, 'Uttar Badda, Dhaka, Bangladesh', 23.782043, 90.423123, 7, 2, ''),
(59, 'Link Rd, Dhaka, Bangladesh', 23.745727, 90.393648, 7, 2, ''),
(60, 'Gudaraghat', 23.779708, 90.418796, 7, 2, ''),
(61, 'Gulshan 1, Dhaka, Bangladesh', 23.782062, 90.416053, 7, 2, ''),
(62, 'TB Gate Bus Stop, TB Gate Rd, Dhaka, Bangladesh', 23.780213, 90.409404, 7, 2, ''),
(63, 'Wireless More Bus Stop, Bir Uttam AK Khandakar Rd, Dhaka 1212, Bangladesh', 23.780672, 90.405538, 7, 2, ''),
(64, 'Amtali ,Shaheed Tajuddin Ahmed Ave, Dhaka 1212, Bangladesh', 23.775458, 90.399168, 7, 2, ''),
(65, 'Mohakhali Bus Stop, Dhaka, Bangladesh', 23.778239, 90.397739, 7, 2, ''),
(66, 'Nabisco', 23.768937, 90.401385, 7, 2, ''),
(67, 'Bijoy Sarani, Dhaka, Bangladesh', 23.764771, 90.385474, 7, 2, ''),
(68, 'Awlad Hossain Market, Kazi Nazrul Islam Ave, Dhaka 1215, Bangladesh', 23.763027, 90.38944, 7, 2, ''),
(69, 'Nabinagar Bazar Bus Stop, Fatulla, Bangladesh', 23.619711, 90.463335, 8, 2, ''),
(70, 'Bish Mail, Savar, Bangladesh', 23.894674, 90.269634, 8, 2, ''),
(71, 'Prantic Bus Stop,JU, Dhaka - Aricha Hwy, Savar, Bangladesh', 23.889703, 90.272239, 8, 2, ''),
(72, 'Radio Colony Bus Stop, Dhaka - Aricha Hwy, Savar, Bangladesh', 23.858745, 90.262358, 8, 2, ''),
(73, 'Savar Bazar, Savar, Bangladesh', 23.850077, 90.25907, 8, 2, ''),
(74, 'Savar Thana Bus Station, Dhaka - Aricha Hwy, Savar, Bangladesh', 23.839529, 90.257713, 8, 2, ''),
(75, 'Hemayetpur Bus Stand, Hemayetpur, Bangladesh', 23.793326, 90.271127, 8, 2, ''),
(76, 'Gabtoli, Bangladesh', 23.783726, 90.344245, 8, 2, ''),
(77, 'Postgola Cantonment,Dhaka-Narayanganj Rd, Dhaka, Bangladesh', 23.689429, 90.428721, 9, 2, ''),
(78, 'Jurain, Dhaka, Bangladesh', 23.688272, 90.443162, 9, 2, ''),
(79, 'Muradpur CNG Station, Dhaka, Bangladesh', 23.692732, 90.444341, 9, 2, ''),
(80, 'Dholaipar More', 23.702689, 90.438427, 9, 2, ''),
(81, 'Mir Hazir Bagh Bus Stop, Dhaka, Bangladesh', 23.705882, 90.431216, 9, 2, ''),
(82, 'Dayaganj Temple, Dhaka, Bangladesh', 0, 90.423712, 9, 2, ''),
(83, 'Dayaganj Mor, Dhaka, Bangladesh', 0, 90.423712, 9, 2, ''),
(84, 'Tikatuli Flyover Connection Lane', 23.720314, 90.422534, 9, 2, ''),
(85, 'Salauddin Bhaban, House No. 44/A, Mayor Mohammad Hanif Flyover, Dhaka 1203, Bangladesh', 23.716955, 90.420108, 9, 2, ''),
(86, 'Sign Board Bus Stop, Dhaka - Narayanganj Rd, Dhaka, Bangladesh', 23.693685, 90.480834, 10, 2, ''),
(87, 'Jalkuri Bus Stop, Jalkury, Dhaka - Narayanganj Rd, Bangladesh', 23.663766, 90.486888, 10, 2, ''),
(88, 'Shibu Market , Fatulla', 23.644249, 90.493484, 10, 2, ''),
(89, 'Chashara, Narayanganj, Bangladesh', 23.626361, 90.499207, 10, 2, ''),
(90, 'IET School Bus Stop, Narayanganj Hwy, Narayanganj, Bangladesh', 23.63497, 90.511617, 11, 2, ''),
(91, 'Chittagong Road Bus Stop, Shiddhirganj, Bangladesh', 23.697853, 90.509706, 11, 2, ''),
(92, 'Arambagh, Dhaka, Bangladesh', 23.730736, 90.418998, 12, 2, ''),
(93, 'Kamalapur Railway Station, kamalapur, Kamalapur Rd, Dhaka 1222, Bangladesh', 23.73202, 90.425922, 12, 2, ''),
(94, 'Rajarbagh, Dhaka, Bangladesh', 23.741159, 90.415464, 12, 2, ''),
(95, 'Malibagh Rail Gate Bus Stop, Dhaka, Bangladesh', 23.750097, 90.413041, 12, 2, ''),
(96, 'Mouchak', 23.745608, 90.411977, 12, 2, ''),
(97, 'Wireless Railgate Bara Moghbazar, Dhaka, Bangladesh', 0, 90.408159, 12, 2, ''),
(98, 'Rampura TV Centre', 23.765164, 90.418977, 13, 2, ''),
(99, 'Rampura Bazar', 23.760395, 90.41863, 13, 2, ''),
(100, 'Hazipara Petrol Pump', 23.757052, 90.417201, 13, 2, ''),
(101, 'Malibagh community center', 23.749626, 90.416288, 13, 2, ''),
(102, 'Khilgaon Policefari', 23.74629, 90.426106, 13, 2, ''),
(103, 'Farmgate Bus Stop, Dhaka 1215, Bangladesh', 23.757273, 90.389996, 4, 2, ''),
(104, 'Bijoy Sarani, Dhaka, Bangladesh', 23.764771, 90.385474, 4, 2, ''),
(105, 'Birshreshto Shaheed Jahangir Gate,Shaheed Sharani, Dhaka, Bangladesh', 23.775392, 90.389876, 4, 2, ''),
(106, 'Mohakhali Bus Stop, Dhaka, Bangladesh', 23.778239, 90.397739, 4, 2, ''),
(107, 'Banani, Dhaka, Bangladesh', 23.793993, 90.404272, 4, 2, ''),
(108, 'MES Bus Stop, Dhaka, Bangladesh', 23.816136, 90.405322, 4, 2, ''),
(109, 'Shewra Bus Stop, Dhaka, Bangladesh', 23.819137, 90.415008, 4, 2, ''),
(110, 'Bishwa Road Bus Stop, Tongi Diversion Rd, Dhaka, Bangladesh', 23.821414, 90.418451, 4, 2, ''),
(111, 'Khilkhet, Dhaka, Bangladesh', 23.831122, 90.424301, 4, 2, ''),
(112, 'Hazrat Shahjalal International Airport, Airport Road, Sector 1, Kurmitola, Dhaka 1229, Bangladesh', 23.846615, 90.402623, 4, 2, ''),
(113, 'Jasimuddin Bus Stop, Dhaka 1230, Bangladesh', 23.860852, 90.400158, 4, 2, ''),
(114, 'Rajlakshmi Bus Stop, Dhaka - Mymensingh Hwy, Dhaka 1230, Bangladesh', 23.863762, 90.400183, 4, 2, ''),
(115, 'Azampur Local Bus Stop, Dhaka 1230, Bangladesh', 23.868364, 90.400427, 4, 2, ''),
(116, 'House Building Bus Stop, Dhaka - Mymensingh Hwy, Dhaka 1230, Bangladesh', 23.873722, 90.400733, 4, 2, ''),
(117, 'Abdullahpur Bus Stop, Dhaka - Ashulia Hwy, Dhaka 1230, Bangladesh', 23.879751, 90.401143, 4, 2, ''),
(118, 'College Gate Bus Stop, Dhaka - Mymensingh Hwy, Tongi, Bangladesh', 23.908806, 90.398099, 4, 2, ''),
(119, 'Board Bazar Bus Stop, Dhaka - Mymensingh Hwy, Bangladesh', 23.945287, 90.382715, 4, 2, ''),
(120, 'Shib Bari Bus Stand, Joydebpur Rd, Joydebpur, Bangladesh', 23.996777, 90.417025, 4, 2, ''),
(121, 'Chowrasta - Joydebpur Rd, Joydebpur, Bangladesh', 23.998997, 90.419802, 4, 2, ''),
(122, 'Maleker Bari Bus Stop, Dhaka - Mymensingh Hwy, Bangladesh', 23.96623, 90.380155, 4, 2, ''),
(123, 'Tongi Bazar Bus Stop, Dhaka - Mymensingh Hwy, Tongi 1230, Bangladesh', 23.884197, 90.400542, 4, 2, '');
-- --------------------------------------------------------
--
-- Table structure for table `places_request`
--
CREATE TABLE `places_request` (
`id` int(11) NOT NULL,
`update_type` int(11) NOT NULL DEFAULT '0',
`stoppage_name` varchar(600) COLLATE utf8_unicode_ci NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`bus_id` int(11) NOT NULL,
`stoppage_type` int(11) NOT NULL,
`remarks` varchar(600) COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(11) NOT NULL,
`requested_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `places_request`
--
INSERT INTO `places_request` (`id`, `update_type`, `stoppage_name`, `lat`, `lng`, `bus_id`, `stoppage_type`, `remarks`, `user_id`, `requested_on`) VALUES
(1, 0, 'Mirpur-1', 23.795604, 90.353655, 1, 2, '', 2, '2017-05-08 05:01:57');
-- --------------------------------------------------------
--
-- Table structure for table `reports1`
--
CREATE TABLE `reports1` (
`id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`time` datetime NOT NULL,
`pos_cnt` int(11) NOT NULL,
`neg_cnt` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `reports1`
--
INSERT INTO `reports1` (`id`, `bus_id`, `user_id`, `lat`, `lng`, `time`, `pos_cnt`, `neg_cnt`) VALUES
(6, 1, 1, 23.7788091, 90.3600887, '2017-05-08 07:59:19', 0, 0),
(5, 1, 1, 23.802953, 90.35167, '2017-05-07 22:34:00', 1, 0),
(4, 1, 1, 23.7786638, 90.35993899999994, '2017-04-30 04:51:53', 1, 0),
(7, 1, 1, 23.7788091, 90.3600887, '2017-05-08 07:59:19', 0, 0),
(8, 1, 1, 23.7788084, 90.3603828, '2017-05-08 08:01:07', 0, 0),
(9, 1, 1, 23.7788084, 90.3603828, '2017-05-08 08:01:42', 0, 0),
(10, 1, 1, 23.7752648, 90.3650895, '2017-05-08 08:03:13', 0, 0),
(11, 1, 1, 23.7752648, 90.3650895, '2017-05-08 08:07:39', 0, 0);
-- --------------------------------------------------------
--
-- Table structure for table `reports2`
--
CREATE TABLE `reports2` (
`id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`time` datetime NOT NULL,
`pos_cnt` int(11) NOT NULL,
`neg_cnt` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `reports2`
--
INSERT INTO `reports2` (`id`, `bus_id`, `user_id`, `lat`, `lng`, `time`, `pos_cnt`, `neg_cnt`) VALUES
(1, 2, 2, 23.728762, 90.399171, '2017-05-08 09:44:28', 1, 0),
(2, 2, 2, 23.733010099999998, 90.3983921, '2017-05-08 10:58:09', 0, 0);
-- --------------------------------------------------------
--
-- Table structure for table `reports3`
--
CREATE TABLE `reports3` (
`id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`time` datetime NOT NULL,
`pos_cnt` int(11) NOT NULL,
`neg_cnt` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `reports4`
--
CREATE TABLE `reports4` (
`id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`time` datetime NOT NULL,
`pos_cnt` int(11) NOT NULL,
`neg_cnt` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `reports5`
--
CREATE TABLE `reports5` (
`id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`time` datetime NOT NULL,
`pos_cnt` int(11) NOT NULL,
`neg_cnt` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `reports6`
--
CREATE TABLE `reports6` (
`id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`time` datetime NOT NULL,
`pos_cnt` int(11) NOT NULL,
`neg_cnt` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `reports7`
--
CREATE TABLE `reports7` (
`id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`time` datetime NOT NULL,
`pos_cnt` int(11) NOT NULL,
`neg_cnt` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `reports8`
--
CREATE TABLE `reports8` (
`id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`time` datetime NOT NULL,
`pos_cnt` int(11) NOT NULL,
`neg_cnt` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `reports9`
--
CREATE TABLE `reports9` (
`id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`time` datetime NOT NULL,
`pos_cnt` int(11) NOT NULL,
`neg_cnt` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `reports10`
--
CREATE TABLE `reports10` (
`id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`time` datetime NOT NULL,
`pos_cnt` int(11) NOT NULL,
`neg_cnt` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `reports11`
--
CREATE TABLE `reports11` (
`id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`time` datetime NOT NULL,
`pos_cnt` int(11) NOT NULL,
`neg_cnt` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `reports12`
--
CREATE TABLE `reports12` (
`id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`time` datetime NOT NULL,
`pos_cnt` int(11) NOT NULL,
`neg_cnt` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `reports13`
--
CREATE TABLE `reports13` (
`id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`time` datetime NOT NULL,
`pos_cnt` int(11) NOT NULL,
`neg_cnt` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `schedule`
--
CREATE TABLE `schedule` (
`id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL,
`trip_type` int(11) NOT NULL,
`time` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`endpoint` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`driver` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`bus_number` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
`comment` varchar(1000) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `schedule`
--
INSERT INTO `schedule` (`id`, `bus_id`, `trip_type`, `time`, `endpoint`, `driver`, `bus_number`, `comment`) VALUES
(1, 14, 0, '7.10 am ', 'Norshingdi', '', '', ''),
(3, 8, 0, '6.20am', 'Nabinogor', '', '', ''),
(4, 1, 0, '6.40am', 'Mirpur-12', 'Shamim', '1325', ''),
(5, 1, 0, '6.40am', 'Mirpur-12', 'Rokibul Hasan', '6199 ', ''),
(6, 1, 0, '7.30am', 'Mirpur-12', 'Salam', '5992', ''),
(7, 1, 0, '7.30am', 'Mirpur-12', 'Aziz', '1391', ''),
(8, 1, 0, '8.30am', 'Mirpur-12', 'Kawser', '1329', ''),
(9, 1, 0, '8.30am', 'Mirpur-12', 'Motaleb', '6042', ''),
(10, 1, 0, '9.50am', 'Mirpur-12', 'Robiul', '1271', ''),
(11, 1, 0, '9.50am', 'Mirpur-12', 'Rokibul Hasan', '6199', ''),
(12, 1, 1, '12:30pm', 'Mirpur-12', 'Salam Junior', '5993', ''),
(13, 1, 1, '1:15pm', 'Mirpur-12', 'Rokibul Hasan', '6199', ''),
(14, 1, 1, '2:10pm', 'Mirpur-12', 'Aziz', '1391', ''),
(15, 1, 1, '3:20pm', 'Mirpur-12', 'Robiul', '1271', ''),
(16, 1, 1, '4:30pm', 'Mirpur-12', 'Kawser', '1329', ''),
(17, 1, 1, '5:00pm', 'Mirpur-12', 'Motaleb', '6042', ''),
(18, 1, 1, '5:30pm', 'Mirpur-12', 'Salam', '5992', ''),
(19, 2, 0, '6.35am', 'Kochukhet', '', '11-1349', ''),
(20, 2, 0, '6.50am', 'Kochukhet', '', '11-1289', 'Ullash Sticker'),
(21, 2, 0, '7.30am', 'Kochukhet', '', '11-0451', ''),
(22, 2, 0, '8.00am', 'Kochukhet', '', '11-1353', ''),
(23, 2, 0, '9.00am', 'Kochukhet', '', '', ''),
(24, 2, 0, '9.45am', 'Kochukhet', '', '11-1349', ''),
(25, 2, 1, '12.20pm', 'Kochukhet', '', '11-6124', ''),
(26, 2, 1, '1.10pm', 'Kochukhet', '', '11-1353', ''),
(27, 2, 1, '2.20pm', 'Kochukhet', '', '11-1349', ''),
(28, 2, 1, '3.30pm', 'Kochukhet', '', '11-0451', ''),
(29, 2, 1, '4.30pm', 'Kochukhet', '', '11-5821', ''),
(30, 2, 1, '5.30pm', 'Kochukhet', '', '11-1353', ''),
(31, 3, 0, '7.00am', 'Mohammadpur', '', '', ''),
(32, 3, 0, '7.30am', 'Moitri Counter', '', '', ''),
(33, 3, 0, '8.00am', 'Moitri Counter', '', '', ''),
(34, 3, 0, '8.30am', 'Mohammadpur', '', '', 'Single Decker'),
(35, 3, 0, '9.00am', 'Mohammadpur', '', '', ''),
(36, 3, 0, '10.00am', 'Mohammadpur', '', '', ''),
(37, 3, 1, '12.15pm', 'Mohammadpur', '', '', ''),
(38, 3, 1, '1.30pm', 'Mohammadpur', '', '', ''),
(39, 3, 1, '2.30pm', 'Mohammadpur', '', '', ''),
(40, 3, 1, '3.30pm', 'Mohammadpur', '', '', 'Single Decker'),
(41, 3, 1, '4.30pm', 'Mohammadpur', '', '', ''),
(42, 3, 1, '5.00pm', 'Mohammadpur', '', '', ''),
(43, 3, 1, '5.30pm', 'Mohammadpur', '', '', ''),
(44, 4, 0, '5.55am', 'Shibbari', '', 'DU Bus', ''),
(45, 4, 0, '6.20am', 'CollegeGate', '', '0755', ''),
(46, 4, 0, '6.30am', 'Shibbari', '', '6057', ''),
(47, 4, 0, '6.35am', 'CollegeGate', '', '5817', ''),
(48, 4, 0, '7.00am', 'CollegeGate', '', '6221', ''),
(49, 4, 0, '7.30am', 'CollegeGate', '', '6124', ''),
(50, 4, 0, '8.30am', 'CollegeGate', '', '5020', 'Single Decker'),
(51, 4, 0, '9.30am', 'CollegeGate', '', '6116', ''),
(52, 4, 1, '12.10pm', 'CollegeGate', '', '6221', ''),
(53, 4, 1, '1.00pm', 'CollegeGate', '', '6116', 'Starts from TSC'),
(54, 4, 1, '1.10pm', 'CollegeGate', '', '0755', ''),
(55, 4, 1, '1.50pm', 'CollegeGate', '', '5817', ''),
(56, 4, 1, '2.20pm', 'Gazipur', '', '6057', ''),
(57, 4, 1, '3.30pm', 'CollegeGate', '', '5800', ''),
(58, 4, 1, '4.15pm', 'CollegeGate', '', '5020', 'Single Decker'),
(59, 4, 1, '5.00pm', 'Gazipur', '', '6124', ''),
(60, 4, 1, '5.30pm', 'CollegeGate', '', '6221', ''),
(61, 5, 0, '7.20am', 'Mugda Stadium', '', 'Double Decker', ''),
(62, 5, 0, '7.20am', 'Bouddho Mondir', '', 'Single Decker', ''),
(63, 5, 0, '8.15am', 'Mugda Stadium', '', 'Double Decker', ''),
(64, 5, 0, '8.15am', 'Bouddho Mondir', '', 'Single Decker', ''),
(65, 5, 0, '9.00am', 'Mugda Stadium', '', 'Double Decker', ''),
(66, 5, 0, '9.00am', 'Bouddho Mondir', '', 'Single Decker', ''),
(67, 5, 0, '10.00am', 'Mugda Stadium', '', 'Double Decker', ''),
(68, 5, 1, '12.05pm', 'VC Chottor', '', 'Double Decker', ''),
(69, 5, 1, '1.30pm', 'TSC', '', 'Double Decker', ''),
(70, 5, 1, '2.20pm', 'VC Chottor', '', 'Double Decker', ''),
(71, 5, 1, '3.40pm', 'TSC', '', 'Double Decker', ''),
(72, 5, 1, '4.30pm', 'TSC', '', 'Double Decker', ''),
(73, 5, 1, '5.20pm', 'TSC', '', 'Double Decker', ''),
(74, 6, 0, '6.40am', 'Meghna ', '', 'Single Decker', 'Stops at Mall Chattar'),
(75, 6, 0, '7.10am', 'Signboard', '', 'Single Decker', 'Stops at Mall Chattar'),
(76, 6, 0, '7.40am', 'Meghna', '', 'Double Decker', 'Stops at Mall Chattar'),
(77, 6, 0, '8.00am', 'Meghna', '', 'Single Decker', 'Stops at Mall Chattar'),
(78, 6, 0, '9.00am', 'Kachpur', '', 'Double Decker', 'Stops at VC Chattar'),
(79, 6, 0, '10.00am', 'Kachpur', '', 'Single Decker', 'Stops at Mall Chattar'),
(80, 6, 0, '10.05am', 'Kachpur', '', 'Single Decker', 'Stops at Mall Chattar'),
(81, 6, 1, '1.15pm', 'Meghna', '', 'Double Decker', 'Starts from VC Chattar'),
(82, 6, 1, '2.30pm', 'Kachpur', '', 'Single Decker', 'Starts from Mall Chattar'),
(83, 6, 1, '4.10pm', 'Kachpur', '', 'Double Decker', 'Starts from Mall Chattar'),
(84, 6, 1, '5.05pm', 'Meghna', '', 'Single Decker', 'Starts from Mall Chattar'),
(85, 6, 1, '5.15pm', 'Meghna', '', 'Double Decker', 'Starts from VC Chattar'),
(86, 7, 0, '6.45am', 'Badda/Gulshan', '', '', ''),
(87, 7, 0, '7.45am', 'Badda/Gulshan', '', '', ''),
(88, 7, 0, '8.40am', 'Badda/Gulshan', '', '', ''),
(89, 7, 1, '1.10pm', 'Badda/Gulshan', '', '', ''),
(90, 7, 1, '4.10pm', 'Badda/Gulshan', '', '', ''),
(91, 7, 1, '5.05pm', 'Badda/Gulshan', '', '', ''),
(92, 8, 0, '7.00am ', 'Nabinogor', '', '', ''),
(93, 8, 0, '8.00am', 'Nabinogor', '', '', ''),
(94, 8, 1, '1.10pm', 'Nabinogor', '', '', 'Starts from Mall Chattar'),
(95, 8, 1, '3.10pm', 'Nabinogor', '', '', 'Starts from Mall Chattar'),
(96, 8, 1, '5.10pm', 'Nabinogor', '', '', 'Starts from Curzon Hall'),
(97, 9, 0, '7.00am', 'Postogola', '', '', ''),
(98, 9, 0, '8.00am', 'Dholaipar', '', '', ''),
(99, 9, 0, '8.00am', 'Postogola', '', '', ''),
(100, 9, 0, '9.00am', 'Postogola', '', '', ''),
(101, 9, 0, '9.35am', 'Postogola', '', '', ''),
(102, 9, 0, '10.00am', 'Postogola', '', '', ''),
(103, 9, 1, '12.10pm', 'Postogola Cantonment', '', '', 'Starts from VC Chottor'),
(104, 9, 1, '1.10pm', 'Postogola Cantonment', '', '', 'Starts from TSC'),
(105, 9, 1, '2.10pm', 'Postogola Cantonment', '', '', 'Starts from VC Chottor'),
(106, 9, 1, '3.10', 'Postogola Cantonment', '', '', 'Starts from VC Chottor'),
(107, 9, 1, '4.10pm', 'Postogola Cantonment', '', '', 'Starts from VC Chottor'),
(108, 9, 1, '5.10pm', 'Postogola Cantonment', '', '', 'Starts from VC Chottor'),
(109, 10, 0, '6.50am', 'Narayanganj', '', 'DU Bus', ''),
(110, 10, 0, '7.50am', 'Narayanganj', '', 'BRTC', ''),
(111, 10, 0, '8.50am', 'Narayanganj', '', 'DU Bus', ''),
(112, 10, 1, '1.05pm', 'Narayanganj', '', 'DU Bus', ''),
(113, 10, 1, '2.30pm', 'Narayanganj', '', 'DU Bus', ''),
(114, 10, 1, '4.05pm', 'Narayanganj', '', 'BRTC', ''),
(115, 10, 1, '5.10pm', 'Narayanganj', '', 'BRTC', ''),
(116, 11, 0, '6.35am', 'IIT School', '', 'Double Decker', 'Stops at VC Chottor'),
(117, 11, 0, '7.15am', 'IIT School', '', 'Double Decker', 'Stops at VC Chottor'),
(118, 11, 0, '8.00am', 'Chittagong Road', '', 'Staff Bus', 'Stops at VC Chottor'),
(119, 11, 0, '8.35am', 'IIT School', '', 'Single Decker', 'Stops at Mall Chottor'),
(120, 11, 1, '1.10pm', 'IIT School', '', 'Single Decker', 'Starts from Mall Chottor'),
(121, 11, 1, '3.10pm', 'IIT School', '', 'Double Decker', 'Starts from VC Chottor'),
(122, 11, 1, '5.05pm', 'Chittagong Road', '', 'Staff Bus', 'Starts from VC Chottor'),
(123, 11, 1, '5.15pm', 'IIT School', '', 'Double Decker', 'Starts from VC Chottor'),
(124, 12, 0, '7.00am', 'Arambagh', '', '', 'Stops before VC Chottor'),
(125, 12, 0, '8.00am', 'Arambagh', '', '', ''),
(126, 12, 0, '8.50am', 'Arambagh', '', '', ''),
(127, 12, 0, '9.50am', 'Arambagh', '', '', ''),
(128, 12, 1, '12.30pm', 'Arambagh', '', '', ''),
(129, 12, 1, '1.45pm', 'Arambagh', '', '', 'Stops before VC Chottor'),
(130, 12, 1, '3.10pm', 'Arambagh', '', '', ''),
(131, 12, 1, '4.10pm', 'Arambagh', '', '', ''),
(132, 12, 1, '5.10pm', 'Arambagh', '', '', ''),
(133, 13, 0, '7.00am', 'Rampura TV Centre', '', '1324', ''),
(134, 13, 0, '7.50am', 'Rampura TV Centre', '', '5973', ''),
(135, 13, 0, '8.40am', 'Rampura TV Centre', '', '6071', ''),
(136, 13, 0, '10.00am', 'Rampura TV Centre', '', '5973', ''),
(137, 13, 1, '12.15pm', 'Rampura TV Centre', '', '5974', ''),
(138, 13, 1, '1.30pm', 'Rampura TV Centre', '', '5992', ''),
(139, 13, 1, '2.35pm', 'Rampura TV Centre', '', '6042', ''),
(140, 13, 1, '3.45pm', 'Rampura TV Centre', '', '5973', ''),
(141, 13, 1, '5.10pm', 'Rampura TV Centre', '', '6199', ''),
(142, 14, 1, '4.00pm', 'Norshingdi', '', '', '');
-- --------------------------------------------------------
--
-- Table structure for table `schedule_request`
--
CREATE TABLE `schedule_request` (
`id` int(11) NOT NULL,
`update_type` int(11) NOT NULL DEFAULT '0',
`old_schedule` int(11) NOT NULL DEFAULT '0',
`bus_id` int(11) NOT NULL,
`trip_type` int(11) NOT NULL,
`time` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`endpoint` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`driver` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`bus_number` varchar(15) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`comment` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`user_id` int(11) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=COMPACT;
-- --------------------------------------------------------
--
-- Table structure for table `stoppage`
--
CREATE TABLE `stoppage` (
`id` int(11) NOT NULL,
`stoppage` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`bus_id` int(11) NOT NULL,
`stoppage_type` int(11) NOT NULL,
`Remarks` varchar(1000) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `stoppage`
--
INSERT INTO `stoppage` (`id`, `stoppage`, `bus_id`, `stoppage_type`, `Remarks`) VALUES
(1, 'চৌরঙ্গী', 1, 2, ''),
(2, 'সেতারা কনভেনশন হল ', 1, 2, ''),
(3, 'ডিজি ল্যাব ', 1, 0, ''),
(4, 'রাব্বানী হোটেল ', 1, 2, ''),
(5, 'অরিজিনাল দশ (হলমার্ক)', 1, 2, ''),
(6, 'প্রশিকা (স্বপ্ন)', 1, 2, ''),
(7, 'মিরপুর ২ (থানার সামনে)', 1, 2, ''),
(8, 'জনতা হাউজিং (BIBM)', 1, 2, ''),
(9, 'মিরপুর এক নাম্বার (সনির সিনেমার বিপরীত পাশে) ', 1, 2, ''),
(10, 'মিরপুর এক নাম্বার (ওভার ব্রিজের আগে), ', 1, 1, ''),
(11, 'মিরপুর এক নাম্বার চাইনিজ ', 1, 2, ''),
(12, 'আনসার ক্যাম্প ', 1, 2, ''),
(13, 'বাঙলা কলেজ (A টাইপ কোয়ার্টারে ঢোকার গলি)', 1, 2, ''),
(14, 'কল্যাণপুর (BRTC টিকেট কাউন্টার)', 1, 0, ''),
(15, 'কল্যাণপুর (ওভার ব্রিজের নিচে),', 1, 1, ''),
(16, 'শ্যামলী ( রোচক মিস্টির দোকান)', 1, 2, ''),
(17, 'টেকনিক্যাল মোড়', 1, 1, ''),
(18, 'কচুক্ষেত ভাগ্যকূল মোড়', 2, 2, ''),
(19, 'পুলপাড় ', 2, 2, ''),
(20, 'মিলি সুপার মার্কেট,', 2, 2, ''),
(21, 'মিরপুর ১৪ নম্বর ', 2, 2, ''),
(22, 'পুলিশ কলেজ ', 2, 2, ''),
(23, 'পুলিশ স্টাফ কলেজ,', 2, 2, ''),
(24, 'মিরপুর ১৩ নম্বর, ', 2, 2, ''),
(25, 'মিরপুর ১০ নম্বর পানির ট্যাংকি, ', 2, 2, ''),
(26, 'মিরপুর ১০ নম্বর শাহজালাল ইসলামী ব্যাংকের পরে', 2, 0, ''),
(27, 'কাজীপাড়া ওভারব্রীজ ', 2, 2, ''),
(28, 'শেওড়াপাড়া বাসস্ট্যান্ড', 2, 2, ''),
(29, ' তালতলা', 2, 2, ''),
(30, ' শেরে বাংলা কৃষি বিশ্ববিদ্যালয় সেকেন্ড গেট ', 2, 2, ''),
(31, 'আল হেলাল এর অপোজিট', 2, 1, ''),
(32, ' মিরপুর ১০ নম্বর ওভার ব্রীজ', 2, 1, ''),
(33, 'নবীনগর ( সাভার )', 8, 2, ''),
(34, 'রেসিডেন্সিয়াল স্কুল (২ নং গেট, ফার্টিলিটি হাসপাতালের বিপরীতে) ', 3, 2, ''),
(35, 'মৈত্রী কাউন্টার(কাজী নজরুল ইসলাম রোডের উত্তর মাথায়, অগ্রণী ব্যাংকের বিপরীতে) ', 3, 0, ''),
(36, 'মোহাম্মদপুর বাস স্ট্যান্ড(বিআরটিসি বাস কাউন্টারের বিপরীতে) ', 3, 2, ''),
(37, 'লালমাটিয়া বাস স্ট্যান্ড(Costly Kabab এর বিপরীতে, লোকাল বাস কাউন্টারের পর)', 3, 0, ''),
(38, '২৭ নাম্বার যাত্রী ছাউনি(State University এর বিপরীতে)', 3, 0, ''),
(39, '১৫ নাম্বার(ইবনে সিনা হসপিটালের পর, কাকলি স্কুলের আগে) ', 3, 0, ''),
(40, 'জিগাতলা (লায়লাতি রেস্টুরেন্টের পর, Chicken King রেস্টুরেন্টের আগে) ', 3, 0, ''),
(41, 'জিগাতলা বাস স্ট্যান্ড ', 3, 1, ''),
(42, '১৫ নাম্বার বাস স্ট্যান্ড', 3, 1, ''),
(43, '১৯ নাম্বার বাস স্ট্যান্ড (স্টার কাবাব)', 3, 2, ''),
(44, 'শঙ্কর বাস স্ট্যান্ড', 3, 1, ''),
(45, 'লালমাটিয়া (সিটি হসপিটালের বিপরীতে, গ্রাফিক আর্টস ইন্সিটিউটের আগে)', 3, 1, ''),
(46, 'নুরজাহান রোড', 3, 1, ''),
(47, 'সলিমুল্লাহ রোড', 3, 1, ''),
(48, 'টাউন হল', 3, 1, ''),
(49, 'আই.ই.টি স্কুল(আদমজী)', 11, 2, ''),
(50, 'চিটাগাংরোড', 11, 2, ''),
(51, 'মুগদাপাড়া', 5, 2, ''),
(52, 'বৌদ্ধ মন্দির', 5, 2, ''),
(53, 'বাসাবো', 5, 2, ''),
(54, 'খিলগাঁও রেলগেট', 5, 2, ''),
(55, 'মানিকনগর', 5, 1, ''),
(56, 'পোস্তগোলা ক্যান্টনমেন্ট', 9, 2, ''),
(57, 'জুরাইন আজিজিয়া মিষ্টান্ন', 9, 0, ''),
(58, 'মুরাদপুর সিএনজি স্টেশন', 9, 0, ''),
(59, 'ধোলাইপাড় মোড়', 9, 0, ''),
(60, 'মীরহাজীরবাগ জোছনা হোটেলের বিপরীতে', 9, 2, ''),
(61, 'নবীনগর', 9, 2, ''),
(62, 'দয়াগঞ্জ মন্দির', 9, 0, ''),
(63, 'টিকাটুলি', 9, 0, ''),
(64, 'সালাউদ্দিন হাসপাতাল', 9, 0, ''),
(65, 'জুরাইন ক্রসিং', 9, 1, ''),
(66, 'টিকাটুলি ফ্লাইওভার কানেকশন লেন', 9, 1, ''),
(67, 'ধোলাইপাড়', 9, 1, ''),
(68, 'দয়াগঞ্জ মোড়', 9, 1, ''),
(69, 'রামপুরা টিভি সেন্টার', 13, 2, ''),
(70, 'রামপুরা বাজার', 13, 2, ''),
(71, 'হাজীপাড়া পেট্রোল পাম্প', 13, 2, ''),
(72, 'মালিবাগ কমিউনিটি সেন্টার', 13, 2, ''),
(73, 'খিলগাঁও পুলিশফাঁড়ি', 13, 2, ''),
(74, 'ফার্মগেট', 7, 2, ''),
(75, 'Farm gate ', 4, 2, ''),
(76, 'Bijoy shoroni', 4, 2, ''),
(77, 'Jahangir gate ', 4, 2, ''),
(78, 'Mohakhali', 4, 2, ''),
(79, 'Banani', 4, 2, ''),
(80, 'Mes', 4, 2, ''),
(81, 'Sheora', 4, 2, ''),
(82, 'Bishshoroad', 4, 2, ''),
(83, 'Khilkhet', 4, 2, ''),
(84, 'Airport', 4, 2, ''),
(85, 'Jasimuddin', 4, 2, ''),
(86, 'Rajlakhhi', 4, 2, ''),
(87, 'Ajampur', 4, 2, ''),
(88, 'House building', 4, 2, ''),
(89, 'Abdullahpur', 4, 2, ''),
(90, 'Station gate', 4, 2, ''),
(91, 'College gate ( Tongi )', 4, 2, ''),
(92, 'Board Bazar', 4, 2, ''),
(93, 'Shibbari', 4, 2, ''),
(94, 'Chowrasta (Gazipur)', 4, 2, ''),
(95, 'ফার্মগেট', 4, 2, ''),
(96, 'বিজয় সরণী', 4, 2, ''),
(97, 'জাহাঙ্গীর গেট', 4, 2, ''),
(98, 'মহাখালী', 4, 2, ''),
(99, 'বনানী', 4, 2, ''),
(100, 'এম,ই,এস', 4, 2, ''),
(101, 'শেওড়া', 4, 2, ''),
(102, 'বিশ্বরোড', 4, 2, ''),
(103, 'খিলক্ষেত', 4, 2, ''),
(104, 'এয়ারপোর্ট', 4, 2, ''),
(105, 'জসীমউদ্দীন', 4, 2, ''),
(106, 'রাজলক্ষ্মী', 4, 2, ''),
(107, 'আজমপুর', 4, 2, ''),
(108, 'হাউজ বিল্ডিং', 4, 2, ''),
(109, 'আব্দুল্লাহপুর', 4, 2, ''),
(110, 'স্টেশন গেট', 4, 2, ''),
(111, 'কলেজগেট ( টঙ্গী )', 4, 2, ''),
(112, 'বোর্ড বাজার', 4, 2, ''),
(113, 'শিববাড়ী', 4, 2, ''),
(114, 'চৌরাস্তা ( গাজীপুর )', 4, 2, ''),
(115, 'কাজলা', 6, 2, ''),
(116, 'শনির আখরা', 6, 2, ''),
(117, 'রায়েরবাগ', 6, 2, ''),
(118, 'মাতুয়াইল মেডিকেল', 6, 2, ''),
(119, 'সাদ্দাম মার্কেট', 6, 2, ''),
(120, 'সাইনবোর্ড', 6, 2, ''),
(121, 'সানারপার ', 6, 2, ''),
(122, 'মৌচাক', 6, 2, ''),
(123, 'চিটাগাং রোড', 6, 2, ''),
(124, 'কাঁচপুর ', 6, 2, ''),
(125, 'মদনপুর', 6, 2, ''),
(126, 'সোনারগাঁ ', 6, 2, ''),
(127, 'মেঘনা', 6, 2, ''),
(128, 'আরামবাগ', 12, 2, ''),
(129, 'কমলাপুর', 12, 2, ''),
(130, 'পীরজঙ্গী মাজার', 12, 2, ''),
(131, 'রাজারবাগ', 12, 2, ''),
(132, 'মালিবাগ', 12, 2, ''),
(133, 'মৌচাক', 12, 2, ''),
(134, 'ওয়ারলেস', 12, 2, ''),
(135, 'সাইনবোর্ড ', 10, 2, ''),
(136, 'জালকুড়ি', 10, 2, ''),
(137, 'শিবু মার্কেট ', 10, 2, ''),
(138, 'চাষাড়া', 10, 2, ''),
(139, 'কাওলা ', 4, 2, ''),
(140, 'kawla', 4, 2, ''),
(141, 'বিশ্বরোড', 2, 4, ''),
(142, 'Bisshoroad', 2, 4, ''),
(143, 'বড়বাড়ি', 4, 2, ''),
(144, 'borobari', 4, 2, ''),
(145, 'মালেকের বাড়ি', 4, 2, ''),
(146, 'Maleker Bari', 4, 2, ''),
(147, 'টঙ্গী বাজার', 4, 2, ''),
(148, 'Tongi Bazar', 4, 2, ''),
(149, 'নতুন বাজার', 7, 2, ''),
(150, 'বাশতলা', 7, 2, ''),
(151, 'শাহজাদপুর', 7, 2, ''),
(152, 'সুভাস্তু নজর ভ্যালী', 7, 2, ''),
(153, 'উত্তর বাড্ডা', 7, 2, ''),
(154, 'লিংক রোড', 7, 2, ''),
(155, 'গুদারাঘাট', 7, 2, ''),
(156, 'গুলশান-১', 7, 2, ''),
(157, 'টিবি গেট ', 7, 2, ''),
(158, 'ওয়ারলেস গেট', 7, 2, ''),
(159, 'আমতলী', 7, 2, ''),
(160, 'মহাখালী(রেল ক্রস)', 7, 2, ''),
(161, 'নাবিস্কো', 7, 2, ''),
(162, 'বিজয় স্মরণী', 7, 1, ''),
(163, 'আওলাদ হোসেন মার্কেট।', 7, 2, ''),
(164, 'nobinogor', 8, 2, ''),
(165, '20 mile', 8, 2, ''),
(166, 'bish mile', 8, 2, ''),
(167, 'JU prantik', 8, 2, ''),
(168, 'C and B ', 8, 2, ''),
(169, 'radio colony ', 8, 2, ''),
(170, 'savar ', 8, 2, ''),
(171, 'thana stand ', 8, 2, ''),
(172, 'hemayetpur ', 8, 2, ''),
(173, 'gabtoli', 8, 2, ''),
(174, 'নবীনগর', 8, 2, ''),
(175, '২০ মাইল', 8, 2, ''),
(176, 'বিশ মাইল', 8, 2, ''),
(177, 'সি এন্ড বি', 8, 2, ''),
(178, 'প্রান্তিক ( জাহাঙ্গীরনগর )', 8, 2, ''),
(179, 'রেডিও কলোনী', 8, 2, ''),
(180, 'সাভার', 8, 2, ''),
(181, 'থানা স্ট্যান্ড', 8, 2, ''),
(182, 'হেমায়েতপুর', 8, 2, ''),
(183, 'গাবতলী', 8, 2, '');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`reg_no` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`mob_no` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`dept_id` int(11) NOT NULL DEFAULT '0',
`status` int(11) NOT NULL,
`code` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`url` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`bus_id` int(11) NOT NULL,
`level` int(11) DEFAULT '0',
`level_req` int(11) NOT NULL DEFAULT '0',
`pos_repu` int(11) NOT NULL DEFAULT '0',
`neg_repu` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `name`, `reg_no`, `mob_no`, `email`, `password`, `dept_id`, `status`, `code`, `url`, `bus_id`, `level`, `level_req`, `pos_repu`, `neg_repu`) VALUES
(1, 'Fahim', '2013312035', '01521430883', 'fahim6119@gmail.com', '$2a$10$a8UbjgEB.R3rlmcnLxszourLXQBCVcTR5ET87qJzpAO8lYsXzfOti', 71, 2, '522533', NULL, 1, 2, 1, 2, 0),
(2, 'Fahad Arefin', '1995312035', '', 'f.arefin8@gmail.com', '$2a$10$WhUyUhfi.jKGE/AdUhW5bOvcQq3ff67VMGlO6E.kPJibGxbySKr3C', 0, 2, '457260', NULL, 2, 0, 1, 11, 0),
(3, 'Nafis Sazid', '2013212072', '', 'nafissazid4820@gmail.com', '$2a$10$6Ax5qHTEw8Rr3YhylXonnuQnK5atGMRYXTFlxD/MoJZ6alZiZNyU.', 0, 2, '228075', NULL, 1, 0, 0, 0, 0),
(4, 'Abida', '2013814911', '', 'abida1616@gmail.com', '$2a$10$joE9mYSulWPFNkEXfgJ9yuyuAa.QoEton3u1jTn8LQiZ4InaiDrQG', 0, 2, '864924', NULL, 12, 0, 0, 0, 0),
(5, 'asdf', '2016435987', '01566334455', 'asd@asd.asd', '$2a$10$1rrltxG6qQgUoxJfjkfmxuAvYSzVid7IokXJVfixgi6fd7sE2K8u6', 83, 1, '980313', NULL, 0, 0, 0, 0, 0),
(6, 'shourav', '2013212542', '', 'shourav95.ri@gmail.com', '$2a$10$bQdZmg/HBQJdMJfr.hg7I.4jndrIJSNyE.BH4ZHmb8RssH2NWIYju', 0, 2, '163912', NULL, 6, 0, 0, 0, 0),
(7, 'Tanvir Shahriar Rifat', '2013412512', '', 'rifat.csedu20@gmail.com', '$2a$10$a5Y.o9A6Jdr76u4kVRasCeBqf1ni.rCxKsjQDxgsq.nQwN/iEnyYS', 0, 1, '136059', NULL, 2, 0, 0, 0, 0),
(8, 'melody_43', '2013712068', '', 'cleopatra.sopto7@gmail.com', '$2a$10$hJWRaJS0NhrGwk5KyrIJwewLUnHop9zTPpk.C4Rm4YgTvbSNAZPOW', 0, 1, '649153', NULL, 12, 0, 0, 0, 0),
(9, 'Nafis Sazid', '2013212073', '', 'nafissazid48@gmail.com', '$2a$10$lkqtEUcnh.YTJCboCXinF.sEZCg92BKQOc2HuuM1gPQxE7zOZI5iC', 0, 2, '167956', NULL, 1, 0, 0, 0, 0),
(10, 'game', '1234456789', '', 'game@mail.com', '$2a$10$zODwqjUxZyJR8fSKbuUQ5OFbLcJV2YS4.j3djaUvdamwPMNjM6wxK', 0, 1, '365710', NULL, 7, 0, 0, 0, 0),
(11, 'Tausif', '0192784486', '', 'tausiftt5238@gmail.com', '$2a$10$.n.sX.pYBHvqQTrcYLE.iO/Olnhl/hVdi36i3Atgw0Y8jc.AOjIpy', 0, 2, '406125', NULL, 4, 0, 0, 0, 0),
(12, 'Meha Masum', '2013812030', '', 'mehamasum@gmail.com', '$2a$10$koCmxFkPhVl89qA1zx5La.rBVdJLD.sNO30/Xj7hGH9MuQnDJmdGK', 0, 2, '329129', NULL, 5, 0, 1, 0, 0),
(13, 'mehedi hasan', '2015454343', '', 'mehedi1055@gmail.com', '$2a$10$frq91AVTbRIY5DTJ4LWpIeZRR1gjt8/IHqXvC3NPcUZX9SpoM4dq.', 0, 2, '343145', NULL, 5, 0, 0, 0, 0);
-- --------------------------------------------------------
--
-- Table structure for table `votes`
--
CREATE TABLE `votes` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`bus_id` int(11) NOT NULL,
`report_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `votes`
--
INSERT INTO `votes` (`id`, `user_id`, `bus_id`, `report_id`) VALUES
(4, 13, 1, 5),
(3, 9, 1, 4),
(5, 2, 2, 1);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `bus`
--
ALTER TABLE `bus`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `bus_request`
--
ALTER TABLE `bus_request`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `depts`
--
ALTER TABLE `depts`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `following`
--
ALTER TABLE `following`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `places`
--
ALTER TABLE `places`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `places_request`
--
ALTER TABLE `places_request`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `reports1`
--
ALTER TABLE `reports1`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `reports2`
--
ALTER TABLE `reports2`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `reports3`
--
ALTER TABLE `reports3`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `reports4`
--
ALTER TABLE `reports4`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `reports5`
--
ALTER TABLE `reports5`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `reports6`
--
ALTER TABLE `reports6`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `reports7`
--
ALTER TABLE `reports7`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `reports8`
--
ALTER TABLE `reports8`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `reports9`
--
ALTER TABLE `reports9`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `reports10`
--
ALTER TABLE `reports10`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `reports11`
--
ALTER TABLE `reports11`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `reports12`
--
ALTER TABLE `reports12`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `reports13`
--
ALTER TABLE `reports13`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `schedule`
--
ALTER TABLE `schedule`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `schedule_request`
--
ALTER TABLE `schedule_request`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `stoppage`
--
ALTER TABLE `stoppage`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `votes`
--
ALTER TABLE `votes`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `bus`
--
ALTER TABLE `bus`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15;
--
-- AUTO_INCREMENT for table `bus_request`
--
ALTER TABLE `bus_request`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `depts`
--
ALTER TABLE `depts`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=94;
--
-- AUTO_INCREMENT for table `following`
--
ALTER TABLE `following`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=36;
--
-- AUTO_INCREMENT for table `places`
--
ALTER TABLE `places`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=124;
--
-- AUTO_INCREMENT for table `places_request`
--
ALTER TABLE `places_request`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `reports1`
--
ALTER TABLE `reports1`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
--
-- AUTO_INCREMENT for table `reports2`
--
ALTER TABLE `reports2`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `reports3`
--
ALTER TABLE `reports3`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `reports4`
--
ALTER TABLE `reports4`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `reports5`
--
ALTER TABLE `reports5`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `reports6`
--
ALTER TABLE `reports6`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `reports7`
--
ALTER TABLE `reports7`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `reports8`
--
ALTER TABLE `reports8`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `reports9`
--
ALTER TABLE `reports9`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `reports10`
--
ALTER TABLE `reports10`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `reports11`
--
ALTER TABLE `reports11`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `reports12`
--
ALTER TABLE `reports12`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `reports13`
--
ALTER TABLE `reports13`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `schedule`
--
ALTER TABLE `schedule`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=143;
--
-- AUTO_INCREMENT for table `schedule_request`
--
ALTER TABLE `schedule_request`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `stoppage`
--
ALTER TABLE `stoppage`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=184;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
--
-- AUTO_INCREMENT for table `votes`
--
ALTER TABLE `votes`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;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 */;
|
alter table netent_transactions add index if not exists netent_transactions_transaction_ref_idx (transaction_ref);
alter table netent_transactions add index if not exists netent_transactions_player_gameround_idx (player_id, game_round_ref);
|
SELECT *
FROM johnny_kelley.warehouse_inventory_jk_01 |
CREATE OR REPLACE VIEW GEO.ADDRESS_BR AS
SELECT L.ID_ADDRESS
, L.ID_NEIGHBORHOOD_CITY
, BM.ID_NEIGHBORHOOD
, BM.ID_CITY
, M.ID_ADM_AREA AS ID_ADM_AREA
, AR.ID_REGION AS ID_REGION
, R.NAME AS REGION
, AR.NAME AS ADM_AREA
, AR.ISO AS ADM_AREA_ISO
, M.NAME AS CITY
, M.ZIPCODE AS CITY_ZIPCODE
, B.NAME AS NEIGHBORHOOD
, L.NAME AS ADDRESS
, L.ZIPCODE AS ADDRESS_ZIPCODE
, L.COMPLEMENT AS ADDRESS_COMPLEMENT
FROM GEO.ADDRESS L
JOIN GEO.NEIGHBORHOOD_CITY BM USING(ID_NEIGHBORHOOD_CITY)
JOIN GEO.NEIGHBORHOOD B USING(ID_NEIGHBORHOOD)
JOIN GEO.CITY M USING(ID_CITY)
JOIN GEO.ADM_AREA AR USING(ID_ADM_AREA)
JOIN GEO.REGION R USING(ID_REGION)
ORDER BY R.NAME
, AR.NAME
, M.NAME
, B.NAME
, L.NAME
, L.COMPLEMENT; |
-- generated by csdl-to-sql for target pgsql from com.opensap.mobile.canteen.csdl.xml
create sequence "canteenServiceNewW4_BookingSet_1_0_id_seq" start with 1 increment by 1;
create table "canteenServiceNewW4_BookingSet_1_0"
(
"BookingDate" timestamp with time zone not null,
"BookingID" serial not null,
"MenuID" bigint not null,
"Price" decimal(10,2) not null,
"Status" varchar(80) not null,
"User" varchar(400) not null,
"row_version" bigint not null,
"is_deleted" boolean not null,
"last_modified" timestamp with time zone not null,
primary key ("BookingID")
);
create index "canteenServiceNewW4_BookingSet_1_0_last_modified_index" on "canteenServiceNewW4_BookingSet_1_0" ("last_modified");
create sequence "canteenServiceNewW4_xs_data_metrics_1_0_id_seq" start with 1 increment by 1;
create table "canteenServiceNewW4_xs_data_metrics_1_0"
(
"id" serial not null,
"start" timestamp with time zone not null,
"period" decimal(20,6) not null,
"process" varchar(400) not null,
"provider" varchar(400) not null,
"component" varchar(800) not null,
"metric" varchar(400) not null,
"unit" varchar(200) not null,
"count" bigint null,
"sum" bigint null,
"average" decimal(25,2) null,
"minimum" bigint null,
"maximum" bigint null,
primary key ("id")
);
create sequence "canteenServiceNewW4_MenuSet_1_0_id_seq" start with 1 increment by 1;
create table "canteenServiceNewW4_MenuSet_1_0"
(
"BookingID" bigint not null,
"CanteenID" bigint not null,
"Dessert" varchar(400) null,
"MainDish" varchar(400) not null,
"MenuID" serial not null,
"Price" decimal(10,2) null,
"Sides" varchar(400) null,
"Soup" varchar(400) null,
"dateOfLunch" timestamp with time zone not null,
"kcalForMain" integer null,
"veggie" boolean null,
"row_version" bigint not null,
"is_deleted" boolean not null,
"last_modified" timestamp with time zone not null,
primary key ("MenuID")
);
create index "canteenServiceNewW4_MenuSet_1_0_last_modified_index" on "canteenServiceNewW4_MenuSet_1_0" ("last_modified");
create table "canteenServiceNewW4_xs_request_history_1_0"
(
"CreationTime" timestamp with time zone not null,
"ResponseStatus" smallint not null,
"ClientID" bytea not null,
"RequestID" bytea not null,
"ResponseHeaders" varchar(4000) not null,
"ResponseData1" bytea null,
"ResponseData2" bytea null,
primary key ("ClientID", "RequestID")
);
create index "canteenServiceNewW4_xs_request_history_1_0_creation_time_index" on "canteenServiceNewW4_xs_request_history_1_0" ("CreationTime");
create sequence "canteenServiceNewW4_CanteenSet_1_0_id_seq" start with 1 increment by 1;
create table "canteenServiceNewW4_CanteenSet_1_0"
(
"CanteenID" serial not null,
"Location" varchar(400) not null,
"Name" varchar(400) not null,
"row_version" bigint not null,
"is_deleted" boolean not null,
"last_modified" timestamp with time zone not null,
primary key ("CanteenID")
);
create index "canteenServiceNewW4_CanteenSet_1_0_last_modified_index" on "canteenServiceNewW4_CanteenSet_1_0" ("last_modified");
|
/*[2]ПЗ Видеоурок - Управление БД. Язык запросов SQL
1. Создайте в домашней директории файл .my.cnf, задав в нем логин и пароль
mkdir /etc/mysql
sudo nano .my.cnf
[mysql]
user=root
password=
2. Создайте базу данных example
*/
/*-- Создать базу данных
create database example;
-- Создать таблицу users, состоящую из двух столбцов, числового id и строкового name
use example;
CREATE TABLE users (
id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
name VARCHAR(200) NOT NULL UNIQUE
);
*/
/*3. Создайте дамп БД example
mysqldump -u root -p example > sample
-- Разверните содержимое дампа в новую БД sample
mysql -u root -p example < sample
*/
|
A SELECT /*+ ORDERED NO_INDEX(c pop90_idx) */
c.city, pop90,
sdo_nn_distance (1) distance_in_miles
FROM geod_interstates i,
geod_cities c
WHERE i.highway = 'I170'
AND sdo_nn(c.location, i.geom,
'sdo_batch_size=10 unit=mile', 1) = 'TRUE'
AND c.pop90 > 300000
AND rownum < 6
ORDER BY distance_in_miles; |
INSERT INTO tourneys (name, attended) VALUES ('Indian Wells', false);
INSERT INTO tourneys (name, attended) VALUES ('Miami Open', false);
INSERT INTO tourneys (name, attended) VALUES ('Roland Garros', false); |
CREATE TABLE oauth_tokens (
id SERIAL PRIMARY KEY NOT NULL,
bearer_token CHAR(64) NOT NULL,
created TIMESTAMP NOT NULL,
scopes TEXT NOT NULL,
owner_id INTEGER NOT NULL,
client_id TEXT NOT NULL,
last_seen TIMESTAMP NOT NULL,
CONSTRAINT bearer_token_uniq UNIQUE(bearer_token)
);
CREATE INDEX bearer_token_idx ON oauth_tokens (bearer_token);
|
create database dvd_db;
use dvd_db;
CREATE TABLE dvd_table(
rowid INTEGER not null AUTO_INCREMENT,
dvdtitle VARCHAR(100) NOT NULL,
inputday datetime NOT NULL,
primary key(rowid)
);
|
# --- !Ups
CREATE TABLE users (
id varchar(36) primary key,
name text NOT NULL,
age integer NOT NULL,
sex text NOT NULL,
enterprise_id varchar(36)
);
CREATE TABLE exps (
id varchar(36) primary key,
name text NOT NULL,
location text NOT NULL,
start_at date NOT NULL,
end_at date,
user_id
);
CREATE TABLE enterprises (
id varchar(36) primary key,
name text NOT NULL,
location text NOT NULL
);
# --- !Downs
DROP TABLE users;
DROP TABLE exps;
DROP TABLE enterprises; |
CREATE TABLE [ERP].[GuiaRemision] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[IdTipoComprobante] INT NULL,
[IdEntidad] INT NULL,
[IdEmpresa] INT NULL,
[IdGuiaRemisionEstado] INT NULL,
[IdMoneda] INT NULL,
[IdEstablecimiento] INT NULL,
[IdChofer] INT NULL,
[IdTransporte] INT NULL,
[IdVehiculo] INT NULL,
[IdAlmacen] INT NULL,
[IdMotivoTraslado] INT NULL,
[IdVale] INT NULL,
[IdUnidadMedida] INT NULL,
[IdModalidadTraslado] INT NULL,
[IdUbigeoOrigen] INT NULL,
[IdUbigeoDestino] INT NULL,
[IdTipoMovimiento] INT NULL,
[TipoCambio] DECIMAL (14, 5) NULL,
[Fecha] DATETIME NULL,
[Serie] VARCHAR (4) NULL,
[Documento] VARCHAR (8) NULL,
[Observacion] VARCHAR (250) NULL,
[NumeroContenedor] VARCHAR (50) NULL,
[CodigoPuerto] VARCHAR (50) NULL,
[CorrelativoAnulacionSunat] INT NULL,
[TicketAnulacion] VARCHAR (250) NULL,
[UsuarioAnulo] VARCHAR (250) NULL,
[FechaAnulado] DATETIME NULL,
[EstablecimientoOrigen] VARCHAR (250) NULL,
[EstablecimientoDestino] VARCHAR (250) NULL,
[PorcentajeIGV] DECIMAL (14, 5) NULL,
[SubTotal] DECIMAL (14, 5) NULL,
[IGV] DECIMAL (14, 5) NULL,
[Total] DECIMAL (14, 5) NULL,
[TotalPeso] DECIMAL (14, 5) NULL,
[Flag] BIT NULL,
[FlagBorrador] BIT NULL,
[FlagGuiaElectronico] BIT NULL,
[FlagValidarStock] BIT NULL,
[UsuarioRegistro] VARCHAR (250) NULL,
[UsuarioModifico] VARCHAR (250) NULL,
[FechaRegistro] DATETIME NULL,
[FechaModificado] DATETIME NULL,
[RutaDocumentoXML] VARCHAR (MAX) NULL,
[RutaDocumentoCDR] VARCHAR (MAX) NULL,
[RutaDocumentoPDF] VARCHAR (MAX) NULL,
[CodigoHash] VARCHAR (MAX) NULL,
[SignatureValue] VARCHAR (MAX) NULL,
[IdListaPrecio] INT NULL,
[IdVendedor] INT NULL,
CONSTRAINT [PK__GuiaRemi__3214EC276447B2C9] PRIMARY KEY CLUSTERED ([ID] ASC),
FOREIGN KEY ([IdListaPrecio]) REFERENCES [ERP].[ListaPrecio] ([ID]),
CONSTRAINT [FK__GuiaRemis__IdEnt__3CCB84FA] FOREIGN KEY ([IdEntidad]) REFERENCES [ERP].[Entidad] ([ID]),
CONSTRAINT [FK__GuiaRemis__IdGui__0E109611] FOREIGN KEY ([IdGuiaRemisionEstado]) REFERENCES [Maestro].[GuiaRemisionEstado] ([ID]),
CONSTRAINT [FK__GuiaRemis__IdMod__63E5521B] FOREIGN KEY ([IdModalidadTraslado]) REFERENCES [XML].[T18ModalidadTraslado] ([ID]),
CONSTRAINT [FK__GuiaRemis__IdMot__6014C137] FOREIGN KEY ([IdMotivoTraslado]) REFERENCES [XML].[T20MotivoTraslado] ([ID]),
CONSTRAINT [FK__GuiaRemis__IdTip__5AE5F7C6] FOREIGN KEY ([IdTipoMovimiento]) REFERENCES [Maestro].[TipoMovimiento] ([ID]),
CONSTRAINT [FK__GuiaRemis__IdUni__6108E570] FOREIGN KEY ([IdUnidadMedida]) REFERENCES [PLE].[T6UnidadMedida] ([ID])
);
|
CREATE TABLE msg_log(
timestamp BIGINT,
msg_id BIGINT,
receiver_id VARCHAR(128),
PRIMARY KEY (timestamp),
INDEX (msg_id),
INDEX (receiver_id)
)ENGINE=MyISAM CHARACTER SET=binary;
|
/**
* Reference: CIS Oracle Database 12c Benchmark v2.0.0 - 12-28-2016
* Prepared By: g4xyk00 (g4xyk00@gmail.com)
**/
/** 1: Oracle Database Installation and Patching Requirements
**/
SELECT * FROM DBA_USERS_WITH_DEFPWD;
SELECT * FROM ALL_USERS;
/** 2: Oracle Parameter Settings
* Listener Settings
* Database Settings
**/
SELECT * FROM V$PARAMETER;
/** 4.2 Database Settings **/
SELECT UPPER(VALUE)
FROM V$PARAMETER
WHERE UPPER(NAME) = 'AUDIT_SYS_OPERATIONS'
OR UPPER(NAME) = 'AUDIT_TRAIL'
OR UPPER(NAME) = 'GLOBAL_NAMES'
OR UPPER(NAME) = 'LOCAL_LISTENER'
OR UPPER(NAME) = 'O7_DICTIONARY_ACCESSIBILITY'
OR UPPER(NAME) = 'OS_ROLES'
OR UPPER(NAME) = 'REMOTE_LISTENER'
OR UPPER(NAME) = 'REMOTE_LOGIN_PASSWORDFILE'
OR UPPER(NAME) = 'REMOTE_OS_AUTHENT'
OR UPPER(NAME) = 'REMOTE_OS_ROLES'
OR UPPER(NAME) = 'UTL_FILE_DIR'
OR UPPER(NAME) = 'SEC_CASE_SENSITIVE_LOGON'
OR UPPER(NAME) = 'SEC_MAX_FAILED_LOGIN_ATTEMPTS'
OR UPPER(NAME) = 'SEC_PROTOCOL_ERROR_FURTHER_ACTION'
OR UPPER(NAME) = 'SEC_PROTOCOL_ERROR_TRACE_ACTION'
OR UPPER(NAME) = 'SEC_RETURN_SERVER_RELEASE_BANNER'
OR UPPER(NAME) = 'SQL92_SECURITY'
OR UPPER(NAME) = '_TRACE_FILES_PUBLIC'
OR UPPER(NAME) = 'RESOURCE_LIMIT';
/** 3: Oracle Connection and Login Restrictions
**/
SELECT * FROM DBA_PROFILES;
SELECT * FROM DBA_USERS;
SELECT * FROM DBA_PROFILES
WHERE RESOURCE_NAME = "FAILED_LOGIN_ATTEMPTS"
OR RESOURCE_NAME = "PASSWORD_LOCK_TIME"
OR RESOURCE_NAME = "PASSWORD_LIFE_TIME"
OR RESOURCE_NAME = "PASSWORD_REUSE_MAX"
OR RESOURCE_NAME = "PASSWORD_REUSE_TIME"
OR RESOURCE_NAME = "PASSWORD_GRACE_TIME"
OR RESOURCE_NAME = "PASSWORD_VERIFY_FUNCTION"
OR RESOURCE_NAME = "SESSIONS_PER_USER";
SELECT USERNAME
FROM DBA_USERS
WHERE PASSWORD='EXTERNAL';
SELECT USERNAME
FROM DBA_USERS
WHERE PROFILE='DEFAULT'
AND ACCOUNT_STATUS='OPEN'
AND USERNAME NOT IN
('ANONYMOUS', 'CTXSYS', 'DBSNMP', 'EXFSYS', 'LBACSYS',
'MDSYS', 'MGMT_VIEW','OLAPSYS','OWBSYS', 'ORDPLUGINS',
'ORDSYS', 'OUTLN', 'SI_INFORMTN_SCHEMA','SYS',
'SYSMAN', 'SYSTEM', 'TSMSYS', 'WK_TEST', 'WKSYS',
'WKPROXY', 'WMSYS', 'XDB', 'CISSCAN');
/** 4: Oracle User Access and Authorization Restrictions
* Default Public Privileges for Packages and Object Types
* Revoke Non-Default Privileges for Packages and Object Types
* Revoke Excessive System Privileges
* Revoke Role Privileges
* Revoke Excessive Table and View Privileges
**/
SELECT * FROM DBA_TAB_PRIVS;
SELECT * FROM DBA_SYS_PRIVS;
SELECT * FROM DBA_ROLE_PRIVS;
SELECT * FROM ALL_TABLES
/** 4.1 Default Public Privileges for Packages and Object Types **/
SELECT GRANTEE,PRIVILEGE,TABLE_NAME
FROM DBA_TAB_PRIVS
WHERE GRANTEE='PUBLIC'
AND PRIVILEGE='EXECUTE'
OR TABLE_NAME='DBMS_ADVISOR'
OR TABLE_NAME='DBMS_CRYPTO'
OR TABLE_NAME='DBMS_JAVA'
OR TABLE_NAME='DBMS_JAVA_TEST'
OR TABLE_NAME='DBMS_JOB'
OR TABLE_NAME='DBMS_LDAP'
OR TABLE_NAME='DBMS_LOB'
OR TABLE_NAME='DBMS_OBFUSCATION_TOOLKIT'
OR TABLE_NAME='DBMS_RANDOM'
OR TABLE_NAME='DBMS_SCHEDULER'
OR TABLE_NAME='DBMS_SQL'
OR TABLE_NAME='DBMS_XMLGEN'
OR TABLE_NAME='DBMS_XMLQUERY'
OR TABLE_NAME='UTL_FILE'
OR TABLE_NAME='UTL_INADDR'
OR TABLE_NAME='UTL_TCP'
OR TABLE_NAME='UTL_MAIL'
OR TABLE_NAME='UTL_SMTP'
OR TABLE_NAME='UTL_DBWS'
OR TABLE_NAME='UTL_ORAMTS'
OR TABLE_NAME='UTL_HTTP'
OR TABLE_NAME='HTTPURITYPE';
/** 4.2 Revoke Non-Default Privileges for Packages and Object Types **/
SELECT GRANTEE,PRIVILEGE,TABLE_NAME
FROM DBA_TAB_PRIVS
WHERE GRANTEE='PUBLIC'
AND PRIVILEGE='EXECUTE'
OR TABLE_NAME='DBMS_SYS_SQL'
OR TABLE_NAME='DBMS_BACKUP_RESTORE'
OR TABLE_NAME='DBMS_AQADM_SYSCALLS'
OR TABLE_NAME='DBMS_REPCAT_SQL_UTL'
OR TABLE_NAME='INITJVMAUX'
OR TABLE_NAME='DBMS_STREAMS_ADM_UTL'
OR TABLE_NAME='DBMS_AQADM_SYS'
OR TABLE_NAME='DBMS_STREAMS_RPC'
OR TABLE_NAME='DBMS_PRVTAQIM'
OR TABLE_NAME='LTADM'
OR TABLE_NAME='WWV_DBMS_SQL'
OR TABLE_NAME='WWV_EXECUTE_IMMEDIATE'
OR TABLE_NAME='DBMS_IJOB'
OR TABLE_NAME='DBMS_FILE_TRANSFER';
/** 4.3 Revoke Excessive System Privileges **/
SELECT GRANTEE, PRIVILEGE
FROM DBA_SYS_PRIVS
WHERE PRIVILEGE='SELECT ANY DICTIONARY'
OR PRIVILEGE='SELECT ANY TABLE'
OR PRIVILEGE='AUDIT SYSTEM'
OR PRIVILEGE='EXEMPT ACCESS POLICY'
OR PRIVILEGE='BECOME USER'
OR PRIVILEGE='CREATE PROCEDURE'
OR PRIVILEGE='ALTER SYSTEM'
OR PRIVILEGE='CREATE ANY LIBRARY'
OR PRIVILEGE='CREATE LIBRARY'
OR PRIVILEGE='GRANT ANY OBJECT PRIVILEGE'
OR PRIVILEGE='GRANT ANY ROLE'
OR PRIVILEGE='GRANT ANY PRIVILEGE';
/** 4.4 Revoke Role Privileges **/
SELECT GRANTEE, GRANTED_ROLE
FROM DBA_ROLE_PRIVS
WHERE granted_role='DELETE_CATALOG_ROLE'
OR granted_role='SELECT_CATALOG_ROLE'
OR granted_role='EXECUTE_CATALOG_ROLE'
OR granted_role='DBA';
/** 4.5 Revoke Excessive Table and View Privileges **/
SELECT GRANTEE, PRIVILEGE
FROM DBA_TAB_PRIVS
WHERE TABLE_NAME='AUD$'
OR TABLE_NAME='USER_HISTORY$'
OR TABLE_NAME='LINK$'
OR TABLE_NAME='USER$'
OR TABLE_NAME LIKE 'DBA_%'
OR TABLE_NAME='SCHEDULER$_CREDENTIAL';
/** 5: Audit/Logging Policies and Procedures
* Traditional Auditing
* Unified Auditing
**/
SELECT * FROM DBA_STMT_AUDIT_OPTS;
SELECT * FROM AUDIT_UNIFIED_POLICIES
SELECT * FROM AUDIT_UNIFIED_ENABLED_POLICIES |
-- @DesviacionRegistrada
-- @TipoResultado
-- En funcion del tipo de Resultado, mostrar.
-- PARAM SALIDA:
-- TotalRendimiento
-- CantPartidos Cantidad de Partidos en la BD en los que ocurrio el caso
-- CantResultadoEsperado
-- CantResultadoContrario
-- Acierto
-- CuotaPromedio
-- Ganancias
-- Perdidas
-- Desviacion Min Porc
-- Desviacion Max Porc |
-- phpMyAdmin SQL Dump
-- version 3.4.5
-- http://www.phpmyadmin.net
--
-- 主机: localhost
-- 生成日期: 2015 年 12 月 10 日 07:36
-- 服务器版本: 5.5.16
-- PHP 版本: 5.3.8
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 */;
--
-- 数据库: `hirourou`
--
-- --------------------------------------------------------
--
-- 表的结构 `hi_info`
--
CREATE TABLE IF NOT EXISTS `hi_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`come_time` int(11) NOT NULL,
`ip` varchar(16) NOT NULL,
`url` varchar(64) NOT NULL,
`browser` varchar(32) NOT NULL,
`screen` varchar(32) NOT NULL,
`sys` varchar(32) NOT NULL,
`ua` varchar(1024) NOT NULL,
`browser_version` varchar(32) NOT NULL,
`title` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;
--
-- 转存表中的数据 `hi_info`
--
INSERT INTO `hi_info` (`id`, `come_time`, `ip`, `url`, `browser`, `screen`, `sys`, `ua`, `browser_version`, `title`) VALUES
(2, 1449722549, '11', 'http://192.168.33.112/zcr/js_anylist/', 'chrome', '1920*1080', 'Windows 7', '2323', '36.0.1985.143', ''),
(3, 1449728956, '192.168.33.112', 'http://192.168.33.112/zcr/js_anylist/', 'firefox', '1920*1080', 'Windows 7', '2323', '42.0', ''),
(4, 1449728975, '192.168.33.112', 'http://192.168.33.112/zcr/js_anylist/', 'firefox', '1920*1080', 'Windows 7', '2323', '42.0', ''),
(5, 1449729353, '192.168.33.112', 'http://192.168.33.112/zcr/js_anylist/', 'firefox', '1920*1080', 'Windows 7', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0', '42.0', '');
/*!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 book(
id INT AUTO_INCREMENT PRIMARY KEY,
isbn CHAR(13) DEFAULT '' NOT NULL,
title TEXT NOT NULL,
publisher VARCHAR(50) DEFAULT '' NOT NULL,
year INT DEFAULT 0 NOT NULL,
price INT DEFAULT 0 NOT NULL,
UNIQUE (isbn)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO book VALUES (1,'9784756144119','The Art of Computer Programming 1',
'アスキー',2004,10290);
INSERT INTO book VALUES (2,'9784756142818','フリーソフトウェアと自由な社会',
'アスキー',2003,3360);
INSERT INTO book VALUES (3,'9784894711631','計算機プログラムの構造と解釈',
'ピアソンエデュケーション',2000,4830);
INSERT INTO book VALUES (4,'9784756136497','プログラミング作法','アスキー',2000,2940);
INSERT INTO book VALUES (5,'9784756140845','ハッカーズ大辞典','アスキー',2002,3990);
CREATE TABLE creator(
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO creator (id,name) VALUES
(1,'Donald E. Knuth'),
(2,'有澤 誠'),
(3,'和田 英一'),
(4,'青木 孝'),
(5,'筧 一彦'),
(6,'鈴木 健一'),
(7,'長尾 高弘'),
(8,'Richard M. Stallman'),
(9,'Gerald Jay Sussman'),
(10,'Julie Sussman'),
(11,'Harold Abelson'),
(12,'Brian Kernighan'),
(13,'Rob Pike'),
(14,'福崎 俊博'),
(15,'Eric S. Raymond'),
(16,'Guy L., Jr. Steele');
CREATE TABLE bookCreator(
id int AUTO_INCREMENT PRIMARY KEY,
bookId INT NOT NULL,
creatorId INT NOT NULL,
role VARCHAR(10) DEFAULT '' NOT NULL,
FOREIGN KEY (bookId) REFERENCES book(id),
FOREIGN KEY (creatorId) REFERENCES creator(id)
) ENGINE=InnoDB;
INSERT INTO bookCreator (bookId,creatorId) VALUES
(1,1), (1,2), (1,3), (1,4), (1,5),
(1,6), (1,7), (2,8), (2,7), (3,9),
(3,10), (3,11), (3,3), (4,12), (4,13),
(4,14), (5,15), (5,14), (5,16);
|
--https://postgres.devmountain.com/
1. --Find all customers with fax numbers and set those numbers to null.
update customer
set fax = null
where fax is not null;
2. --Find all customers with no company (null) and set their company to "Self".
update customer
set company = 'Self'
where company is null;
3. --Find the customer Julia Barnett and change her last name to Thompson.
update customer
set last_name = 'Thompson'
where first_name is 'Julia'
AND last_name is 'Barnett';
4. --Find the customer with this email luisrojas@yahoo.cl and change his support rep to 4.
update customer
set support_rep_id = 4
where email = 'luisrojas@yahoo.cl';
5. --Find all tracks that are the genre Metal and have no composer. Set the composer to "The darkness around us".
update track
set composer = 'The darkness around us'
where genre_id =
(select genre_id from genre where name = 'Metal')
AND composer is null;
6. -- Refresh your page to remove all database changes. |
-- --------------------------------------------------------
-- Host: 127.0.0.1
-- Server version: 10.1.9-MariaDB - mariadb.org binary distribution
-- Server OS: Win32
-- HeidiSQL Version: 9.4.0.5125
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Dumping structure for table gameoforum.thread
CREATE TABLE IF NOT EXISTS `Thread` (
`threadId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`forumId` int(10) unsigned NOT NULL,
`userId` int(10) unsigned NOT NULL,
`title` varchar(100) NOT NULL,
`creationTime` bigint(20) NOT NULL,
PRIMARY KEY (`threadId`),
KEY `forumId` (`forumId`),
KEY `userId` (`userId`)
) ENGINE=MyISAM AUTO_INCREMENT=176 DEFAULT CHARSET=utf8;
-- Dumping data for table gameoforum.thread: 175 rows
/*!40000 ALTER TABLE `Thread` DISABLE KEYS */;
INSERT INTO `Thread` (`threadId`, `forumId`, `userId`, `title`, `creationTime`) VALUES
(1, 2, 33, 'When can I discover the magic?', 1437869506),
(2, 5, 23, 'Where do I obtain most of the zombies?', 1523763576),
(3, 4, 41, 'How many times must I defeat all of the Demon Lords?', 1409844667),
(4, 2, 46, 'How do I discover some of the fruit?', 1423150103),
(5, 1, 29, 'How many times must I check the orcs?', 1420209495),
(6, 3, 17, 'How do I revive all of the Holy Swords?', 1518787613),
(7, 4, 9, 'When can I betray some of the zombies?', 1456818902),
(8, 5, 31, 'With who do I find all of the dragons?', 1467407130),
(9, 1, 7, 'How many times must I find some of the elementals?', 1468947119),
(10, 2, 22, 'How many times must I check most of the magic beans?', 1407716895),
(11, 3, 40, 'Where do I discover all of the dragons?', 1406420300),
(12, 4, 10, 'With who do I betray the elementals?', 1427006668),
(13, 2, 19, 'With who do I check some of the magic?', 1399899556),
(14, 1, 32, 'How do I obtain all of the fruit?', 1523451883),
(15, 4, 31, 'Where do I defeat most of the orcs?', 1464110195),
(16, 2, 35, 'How do I betray most of the goblins?', 1496192450),
(17, 4, 3, 'With who do I plot against most of the zombies?', 1399626494),
(18, 5, 29, 'With who do I check all of the orcs?', 1496739687),
(19, 3, 45, 'When can I obtain all of the insects?', 1511939452),
(20, 4, 41, 'When can I check the goblins?', 1527781033),
(21, 2, 6, 'How do I betray the demons?', 1427353152),
(22, 3, 28, 'Where do I find all of the Holy Swords?', 1402288024),
(23, 4, 48, 'Where do I revive most of the imps?', 1492023417),
(24, 3, 7, 'When can I discover some of the goblins?', 1491536373),
(25, 5, 42, 'How many times must I check most of the pidgeons?', 1432700887),
(26, 3, 41, 'When can I check the Demon Lords?', 1423137811),
(27, 5, 1, 'How do I betray some of the elementals?', 1512365636),
(28, 1, 39, 'With who do I betray the goblins?', 1485975935),
(29, 3, 31, 'How many times must I defeat most of the vampires?', 1409589596),
(30, 3, 16, 'When can I find all of the imps?', 1400407154),
(31, 5, 20, 'How many times must I defeat most of the elementals?', 1521603063),
(32, 2, 31, 'With who do I plot against the orcs?', 1460592518),
(33, 1, 3, 'Where do I revive some of the elementals?', 1491277916),
(34, 5, 35, 'How many times must I defeat most of the zombies?', 1453667767),
(35, 1, 31, 'With who do I revive the goblins?', 1428104872),
(36, 2, 18, 'Where do I check some of the dragons?', 1448028530),
(37, 4, 8, 'With who do I revive the insects?', 1479528552),
(38, 1, 22, 'How many times must I defeat the Demon Lords?', 1413616065),
(39, 5, 19, 'With who do I revive the zombies?', 1502748465),
(40, 1, 23, 'With who do I revive most of the magic?', 1490633561),
(41, 4, 42, 'How many times must I discover the imps?', 1463715879),
(42, 3, 26, 'How do I plot against most of the goblins?', 1485110155),
(43, 1, 26, 'Where do I discover most of the demons?', 1441531239),
(44, 5, 16, 'Where do I defeat most of the lizards?', 1495213908),
(45, 4, 12, 'Where do I betray the vampires?', 1426063653),
(46, 1, 45, 'How do I betray some of the vampires?', 1390432580),
(47, 4, 25, 'Where do I check some of the goblins?', 1487067753),
(48, 4, 37, 'How many times must I betray all of the fruit?', 1434460876),
(49, 4, 12, 'With who do I revive some of the Holy Swords?', 1496934833),
(50, 5, 22, 'How many times must I discover the magic?', 1504621646),
(51, 1, 48, 'With who do I plot against all of the vampires?', 1517901453),
(52, 3, 2, 'Where do I plot against most of the demons?', 1391091432),
(53, 3, 43, 'How many times must I check most of the magic beans?', 1514849605),
(54, 1, 3, 'How do I betray all of the vampires?', 1475288278),
(55, 1, 34, 'When can I plot against most of the lizards?', 1498837226),
(56, 5, 37, 'With who do I check some of the vampires?', 1509888067),
(57, 2, 29, 'How do I betray all of the vampires?', 1396638130),
(58, 1, 27, 'How do I defeat most of the pidgeons?', 1405443696),
(59, 4, 43, 'Where do I find some of the magic beans?', 1469756672),
(60, 5, 23, 'How many times must I discover the lizards?', 1412571588),
(61, 4, 43, 'When can I check some of the imps?', 1423627648),
(62, 1, 13, 'Where do I obtain the goblins?', 1424795770),
(63, 2, 42, 'How many times must I obtain the insects?', 1414196955),
(64, 2, 1, 'How many times must I obtain all of the orcs?', 1441183693),
(65, 5, 10, 'Where do I betray all of the dragons?', 1454677708),
(66, 2, 12, 'How do I check all of the orcs?', 1506707551),
(67, 5, 28, 'How many times must I discover the zombies?', 1467758540),
(68, 2, 44, 'When can I defeat all of the orcs?', 1391304758),
(69, 1, 13, 'How do I find all of the insects?', 1455116385),
(70, 5, 42, 'How many times must I discover the magic?', 1527367493),
(71, 4, 2, 'How many times must I plot against most of the zombies?', 1414924670),
(72, 2, 10, 'How do I plot against all of the insects?', 1458899177),
(73, 1, 11, 'Where do I find most of the demons?', 1412205328),
(74, 3, 40, 'With who do I plot against some of the zombies?', 1487319101),
(75, 4, 26, 'When can I revive some of the demons?', 1460622545),
(76, 4, 13, 'Where do I obtain most of the dragons?', 1437353633),
(77, 1, 10, 'Where do I find all of the vampires?', 1504733480),
(78, 4, 41, 'When can I plot against all of the dragons?', 1481833105),
(79, 1, 6, 'With who do I check the goblins?', 1422576356),
(80, 2, 30, 'With who do I plot against some of the magic beans?', 1426318950),
(81, 2, 1, 'With who do I revive all of the pidgeons?', 1484473493),
(82, 1, 40, 'When can I find most of the insects?', 1493811654),
(83, 5, 45, 'How do I plot against all of the zombies?', 1475793324),
(84, 3, 38, 'Where do I plot against all of the lizards?', 1453654222),
(85, 3, 35, 'Where do I defeat some of the orcs?', 1410329189),
(86, 1, 29, 'How do I check all of the imps?', 1410718305),
(87, 3, 35, 'How many times must I revive some of the magic beans?', 1526892971),
(88, 5, 11, 'With who do I defeat the orcs?', 1515466196),
(89, 4, 36, 'How many times must I revive the magic beans?', 1530204861),
(90, 4, 21, 'With who do I betray most of the dragons?', 1512820587),
(91, 2, 30, 'How many times must I obtain most of the fruit?', 1483902121),
(92, 3, 29, 'When can I plot against all of the pidgeons?', 1476314597),
(93, 4, 6, 'With who do I obtain some of the zombies?', 1460445753),
(94, 3, 49, 'When can I betray some of the orcs?', 1409013650),
(95, 5, 28, 'How many times must I find all of the imps?', 1460983104),
(96, 5, 43, 'Where do I check most of the goblins?', 1526205404),
(97, 4, 41, 'How many times must I find most of the zombies?', 1394933780),
(98, 2, 26, 'When can I betray some of the magic?', 1412427962),
(99, 4, 40, 'With who do I find all of the goblins?', 1437011050),
(100, 3, 35, 'When can I discover some of the vampires?', 1502076278),
(101, 5, 42, 'When can I defeat all of the insects?', 1464325004),
(102, 2, 15, 'How do I discover some of the magic beans?', 1453302359),
(103, 2, 5, 'How many times must I check most of the vampires?', 1453997743),
(104, 2, 11, 'Where do I find some of the vampires?', 1491601246),
(105, 1, 27, 'How do I obtain the demons?', 1486497558),
(106, 3, 36, 'Where do I defeat the fruit?', 1494870354),
(107, 5, 38, 'With who do I plot against some of the fruit?', 1519160692),
(108, 1, 46, 'With who do I find the imps?', 1515884269),
(109, 2, 8, 'How many times must I find some of the orcs?', 1528821492),
(110, 4, 46, 'With who do I betray most of the insects?', 1442146249),
(111, 1, 44, 'How many times must I defeat some of the elementals?', 1513159351),
(112, 3, 45, 'With who do I obtain most of the pidgeons?', 1518800859),
(113, 3, 12, 'How do I betray the dragons?', 1438468373),
(114, 3, 19, 'With who do I plot against the dragons?', 1500148551),
(115, 4, 33, 'When can I revive some of the elementals?', 1506232079),
(116, 1, 10, 'With who do I plot against all of the pidgeons?', 1455396164),
(117, 2, 11, 'When can I revive the pidgeons?', 1391496943),
(118, 2, 24, 'Where do I find some of the Holy Swords?', 1512808697),
(119, 3, 26, 'Where do I revive all of the vampires?', 1435163226),
(120, 3, 12, 'Where do I discover some of the dragons?', 1413811391),
(121, 1, 10, 'With who do I find some of the Demon Lords?', 1514250748),
(122, 5, 37, 'How many times must I obtain all of the fruit?', 1498153710),
(123, 1, 17, 'How many times must I obtain some of the pidgeons?', 1515105142),
(124, 2, 40, 'Where do I find some of the magic beans?', 1415465039),
(125, 2, 28, 'When can I find all of the magic beans?', 1429109164),
(126, 4, 41, 'How many times must I defeat all of the goblins?', 1469213662),
(127, 2, 46, 'With who do I betray most of the insects?', 1530956959),
(128, 1, 46, 'With who do I betray some of the elementals?', 1530162246),
(129, 4, 5, 'Where do I plot against some of the imps?', 1402440262),
(130, 2, 4, 'With who do I revive all of the magic beans?', 1454595983),
(131, 2, 23, 'How many times must I betray most of the insects?', 1407426657),
(132, 5, 7, 'How many times must I check most of the imps?', 1466344372),
(133, 4, 49, 'How do I revive some of the zombies?', 1442288409),
(134, 3, 3, 'When can I obtain the vampires?', 1408621752),
(135, 2, 10, 'When can I betray some of the magic beans?', 1444144764),
(136, 4, 49, 'When can I revive some of the demons?', 1530258964),
(137, 4, 9, 'Where do I plot against all of the dragons?', 1427509476),
(138, 2, 22, 'Where do I revive most of the Demon Lords?', 1525697896),
(139, 4, 4, 'With who do I obtain most of the magic beans?', 1414613174),
(140, 5, 42, 'How many times must I find the dragons?', 1454154324),
(141, 1, 14, 'With who do I defeat the orcs?', 1484926575),
(142, 5, 35, 'How do I find some of the Demon Lords?', 1434775391),
(143, 2, 5, 'When can I check all of the Demon Lords?', 1431797507),
(144, 5, 28, 'Where do I defeat some of the dragons?', 1459036910),
(145, 2, 33, 'Where do I plot against the magic beans?', 1526854857),
(146, 4, 35, 'When can I obtain most of the fruit?', 1445352126),
(147, 1, 27, 'Where do I revive most of the imps?', 1466170712),
(148, 4, 4, 'Where do I check the imps?', 1412784075),
(149, 1, 11, 'How many times must I defeat the pidgeons?', 1483272416),
(150, 5, 22, 'How do I plot against most of the orcs?', 1461002405),
(151, 2, 16, 'When can I find the Holy Swords?', 1422892111),
(152, 4, 40, 'Where do I betray all of the elementals?', 1451022793),
(153, 1, 25, 'With who do I check some of the fruit?', 1503346302),
(154, 4, 36, 'With who do I plot against some of the orcs?', 1398220682),
(155, 4, 47, 'How many times must I discover most of the Holy Swords?', 1438191041),
(156, 1, 50, 'Where do I betray most of the demons?', 1464855883),
(157, 2, 23, 'How do I check the Holy Swords?', 1501543042),
(158, 1, 28, 'When can I obtain the elementals?', 1412572666),
(159, 4, 3, 'When can I defeat all of the pidgeons?', 1478377520),
(160, 5, 49, 'How do I plot against some of the magic beans?', 1457830886),
(161, 2, 33, 'With who do I revive most of the zombies?', 1446165502),
(162, 5, 45, 'How do I discover most of the orcs?', 1443280503),
(163, 4, 38, 'How do I revive some of the elementals?', 1478404090),
(164, 2, 30, 'How do I discover most of the orcs?', 1388786308),
(165, 1, 31, 'When can I obtain some of the magic beans?', 1391967161),
(166, 5, 16, 'How many times must I check the Holy Swords?', 1492860322),
(167, 4, 2, 'With who do I check the fruit?', 1459456665),
(168, 1, 41, 'When can I defeat some of the orcs?', 1436172332),
(169, 5, 36, 'How do I revive most of the dragons?', 1433504204),
(170, 5, 10, 'How many times must I revive the pidgeons?', 1480320400),
(171, 4, 23, 'Where do I find some of the insects?', 1404438533),
(172, 5, 42, 'Where do I betray all of the orcs?', 1441103173),
(173, 2, 46, 'When can I plot against some of the demons?', 1462324517),
(174, 3, 47, 'How do I check some of the demons?', 1419676934),
(175, 1, 34, 'When can I check all of the imps?', 1433464405);
/*!40000 ALTER TABLE `Thread` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
|
DROP VIEW IF EXISTS v_account_context_object, v_booking_context_object,
v_campaign_context_object, v_client_context_object, v_em_mesg_context_object, v_media_content_context_object,
v_segment_context_object, v_site_context_object, v_special_location_context_object, v_user_context_object;
|
UPDATE Klanten.dbo.TblProductUnit
SET NameFra = 'pièce(s)'
WHERE Code='PIECE'
UPDATE Klanten.dbo.TblProductUnit
SET NameFra = 'paire(s)'
WHERE Code='PAIR'
|
SET CLIENT_MIN_MESSAGES = ERROR;
CREATE DOMAIN email_address AS citext
CONSTRAINT valid_email_address CHECK ( VALUE ~ E'^.+@.+(?:\\..+)+' );
CREATE TABLE "Version" (
version INTEGER PRIMARY KEY
);
CREATE UNIQUE INDEX only_one_version_row ON "Version" ((TRUE));
CREATE TYPE date_style AS ENUM ( 'American', 'European', 'YMD' );
CREATE TABLE "User" (
-- will be the same as a person_id
user_id SERIAL8 PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
-- RFC2307 Blowfish crypt
password VARCHAR(67) NOT NULL,
time_zone TEXT NOT NULL DEFAULT 'UTC',
date_style date_style NOT NULL DEFAULT 'American',
use_24_hour_time BOOLEAN DEFAULT FALSE,
creation_datetime TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_modified_datetime TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
is_system_admin BOOLEAN DEFAULT FALSE,
is_disabled BOOLEAN DEFAULT FALSE,
is_system_user BOOLEAN DEFAULT FALSE,
person_id INT8 NULL,
account_id INT8 NULL,
role_id INTEGER NULL,
CONSTRAINT valid_username CHECK ( username != '' ),
CONSTRAINT valid_password CHECK ( password != '' ),
CONSTRAINT account_requires_role
CHECK ( ( account_id IS NULL AND role_id IS NULL )
OR
( account_id IS NOT NULL AND role_id IS NOT NULL ) )
);
CREATE INDEX "User_person_id" ON "User" ("person_id");
CREATE INDEX "User_account_id" ON "User" ("account_id");
CREATE INDEX "User_role_id" ON "User" ("role_id");
CREATE TABLE "Account" (
account_id SERIAL PRIMARY KEY,
name TEXT UNIQUE NOT NULL,
domain_id INTEGER NOT NULL,
default_time_zone TEXT NOT NULL DEFAULT 'UTC',
fiscal_year_start_month INTEGER NOT NULL DEFAULT 1,
creation_datetime TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT valid_name CHECK ( name != '' ),
CONSTRAINT valid_fiscal_year_start_month
CHECK ( fiscal_year_start_month >= 1 AND fiscal_year_start_month <= 12 )
);
CREATE INDEX "Account_domain_id" ON "Account" ("domain_id");
CREATE TABLE "Role" (
role_id SERIAL PRIMARY KEY,
name TEXT UNIQUE NOT NULL
);
CREATE DOMAIN hostname AS citext
CONSTRAINT valid_hostname CHECK ( VALUE ~ E'^[^\\.]+(?:\\.[^\\.]+)+$' );
CREATE TABLE "Domain" (
domain_id SERIAL PRIMARY KEY,
web_hostname hostname UNIQUE NOT NULL,
email_hostname hostname UNIQUE NOT NULL,
requires_ssl BOOLEAN DEFAULT FALSE,
creation_datetime TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT valid_web_hostname CHECK ( web_hostname != '' ),
CONSTRAINT valid_email_hostname CHECK ( email_hostname != '' )
);
CREATE DOMAIN filename AS citext
CONSTRAINT no_slashes CHECK ( VALUE ~ E'^[^\\\\/]+$' );
CREATE TABLE "File" (
file_id SERIAL8 PRIMARY KEY,
mime_type citext NOT NULL,
filename filename NOT NULL,
-- This lets us look up a variation of a file (notably a
-- resized image) by generating a file name from some other
-- File row, rather than having to know its file_id. For most
-- files, this will be the same as its file_id, but for resized
-- images it will be something like 1234-100x100
unique_name citext UNIQUE NULL,
contents BYTEA NOT NULL,
creation_datetime TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
account_id INT8 NOT NULL
);
CREATE INDEX "File_account_id" ON "File" ("account_id");
CREATE TYPE contact_type AS ENUM ( 'Person', 'Organization', 'Household' );
CREATE DOMAIN uri AS TEXT
CONSTRAINT valid_uri CHECK ( VALUE ~ E'^https?://[\\w-_]+(\.[\\w-_]+)*\\.\\w{2,3}' );
CREATE TABLE "Contact" (
contact_id SERIAL8 PRIMARY KEY,
contact_type contact_type NOT NULL,
allows_email BOOLEAN NOT NULL DEFAULT TRUE,
email_opt_out BOOLEAN NOT NULL DEFAULT FALSE,
allows_mail BOOLEAN NOT NULL DEFAULT TRUE,
allows_phone BOOLEAN NOT NULL DEFAULT TRUE,
allows_trade BOOLEAN NOT NULL DEFAULT FALSE,
creation_datetime TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
image_file_id INT8 NULL,
-- an identifier from another app, probably created via an
-- initial import from something else
external_id TEXT UNIQUE NULL,
account_id INTEGER NOT NULL
);
CREATE INDEX "Contact_image_file_id" ON "Contact" ("image_file_id");
CREATE INDEX "Contact_account_id" ON "Contact" ("account_id");
CREATE DOMAIN pos_int AS INTEGER
CONSTRAINT is_positive CHECK ( VALUE > 0 );
CREATE TABLE "CustomFieldGroup" (
custom_field_group_id SERIAL8 PRIMARY KEY,
name citext NOT NULL,
display_order pos_int NOT NULL,
applies_to_person BOOLEAN NOT NULL DEFAULT TRUE,
applies_to_household BOOLEAN NOT NULL DEFAULT FALSE,
applies_to_organization BOOLEAN NOT NULL DEFAULT FALSE,
account_id INT8 NOT NULL,
CONSTRAINT "CustomFieldGroup_account_id_display_order_unique"
UNIQUE ( account_id, display_order )
);
CREATE INDEX "CustomFieldGroup_account_id" ON "CustomFieldGroup" ("account_id");
CREATE TYPE custom_field_type AS
ENUM ( 'Integer', 'Decimal', 'Date', 'DateTime', 'Text', 'File', 'SingleSelect', 'MultiSelect' );
CREATE TABLE "CustomField" (
custom_field_id SERIAL8 PRIMARY KEY,
label TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
type custom_field_type NOT NULL,
is_required BOOLEAN DEFAULT FALSE,
html_widget_id INTEGER NOT NULL,
display_order pos_int NOT NULL,
account_id INT8 NOT NULL,
custom_field_group_id INT8 NOT NULL,
CONSTRAINT "CustomField_custom_field_group_id_display_order_unique"
UNIQUE ( custom_field_group_id, display_order )
);
CREATE INDEX "CustomField_custom_field_group_id"
ON "CustomField" ("custom_field_group_id");
CREATE INDEX "CustomField_html_widget_id"
ON "CustomField" ("html_widget_id");
CREATE TABLE "HTMLWidget" (
html_widget_id SERIAL PRIMARY KEY,
name TEXT UNIQUE NOT NULL,
description TEXT NOT NULL,
type custom_field_type NOT NULL
);
CREATE TABLE "CustomFieldIntegerValue" (
custom_field_id INT8 NOT NULL,
contact_id INT8 NOT NULL,
value INT8 NOT NULL,
PRIMARY KEY ( custom_field_id, contact_id )
);
CREATE INDEX "CustomFieldIntegerValue_custom_field_id"
ON "CustomFieldIntegerValue" ("custom_field_id");
CREATE TABLE "CustomFieldDecimalValue" (
custom_field_id INT8 NOT NULL,
contact_id INT8 NOT NULL,
value FLOAT8 NOT NULL,
PRIMARY KEY ( custom_field_id, contact_id )
);
CREATE INDEX "CustomFieldDecimalValue_custom_field_id"
ON "CustomFieldDecimalValue" ("custom_field_id");
CREATE TABLE "CustomFieldDateValue" (
custom_field_id INT8 NOT NULL,
contact_id INT8 NOT NULL,
value DATE NOT NULL,
PRIMARY KEY ( custom_field_id, contact_id )
);
CREATE INDEX "CustomFieldDateValue_custom_field_id"
ON "CustomFieldDateValue" ("custom_field_id");
CREATE TABLE "CustomFieldDateTimeValue" (
custom_field_id INT8 NOT NULL,
contact_id INT8 NOT NULL,
value TIMESTAMP WITHOUT TIME ZONE NOT NULL,
PRIMARY KEY ( custom_field_id, contact_id )
);
CREATE INDEX "CustomFieldDateTimeValue_custom_field_id"
ON "CustomFieldDateTimeValue" ("custom_field_id");
CREATE TABLE "CustomFieldTextValue" (
custom_field_id INT8 NOT NULL,
contact_id INT8 NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY ( custom_field_id, contact_id )
);
CREATE INDEX "CustomFieldTextValue_custom_field_id"
ON "CustomFieldTextValue" ("custom_field_id");
CREATE TABLE "CustomFieldFileValue" (
custom_field_id INT8 NOT NULL,
contact_id INT8 NOT NULL,
value BYTEA NOT NULL,
PRIMARY KEY ( custom_field_id, contact_id )
);
CREATE INDEX "CustomFieldFileValue_custom_field_id"
ON "CustomFieldFileValue" ("custom_field_id");
CREATE TABLE "CustomFieldSelectOption" (
custom_field_select_option_id INT8 PRIMARY KEY,
custom_field_id INT8 NOT NULL,
display_order pos_int NOT NULL,
value TEXT NOT NULL,
CONSTRAINT "CustomFieldSelectOption_custom_field_id_display_order_unique"
UNIQUE ( custom_field_id, display_order )
);
CREATE INDEX "CustomFieldSelectOption_custom_field_id"
ON "CustomFieldSelectOption" ("custom_field_id");
CREATE TABLE "CustomFieldSingleSelectValue" (
custom_field_id INT8 NOT NULL,
contact_id INT8 NOT NULL,
custom_field_select_option_id INT8 NOT NULL,
PRIMARY KEY ( custom_field_id, contact_id )
);
CREATE INDEX "CustomFieldSingleSelectValue_custom_field_id"
ON "CustomFieldSingleSelectValue" ("custom_field_id");
CREATE INDEX "CustomFieldSingleSelectValue_custom_field_select_option_id"
ON "CustomFieldSingleSelectValue" ("custom_field_select_option_id");
CREATE TABLE "CustomFieldMultiSelectValue" (
custom_field_id INT8 NOT NULL,
contact_id INT8 NOT NULL,
custom_field_select_option_id INT8 NOT NULL,
PRIMARY KEY ( custom_field_id, contact_id, custom_field_select_option_id )
);
CREATE INDEX "CustomFieldMultiSelectValue_custom_field_id"
ON "CustomFieldMultiSelectValue" ("custom_field_id");
CREATE INDEX "CustomFieldMultiSelectValue_custom_field_select_option_id"
ON "CustomFieldMultiSelectValue" ("custom_field_select_option_id");
CREATE TABLE "Email" (
email_id SERIAL8 PRIMARY KEY,
from_contact_id INT8 NULL,
from_user_id INT8 NULL,
donation_id INT8 UNIQUE NULL,
subject TEXT NOT NULL,
raw_email TEXT NOT NULL,
account_id INT8 NULL,
email_datetime TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT valid_subject CHECK ( subject != '' ),
CONSTRAINT valid_raw_email CHECK ( raw_email != '' )
);
CREATE INDEX "Email_from_contact_id" ON "Email" ("from_contact_id");
CREATE INDEX "Email_from_user_id" ON "Email" ("from_user_id");
CREATE INDEX "Email_donation_id" ON "Email" ("donation_id");
CREATE INDEX "Email_account_id" ON "Email" ("account_id");
CREATE TABLE "ContactEmail" (
contact_id INT8 NOT NULL,
email_id INT8 NOT NULL,
PRIMARY KEY ( contact_id, email_id )
);
CREATE INDEX "ContactEmail_email_id" ON "ContactEmail" ("email_id");
CREATE TABLE "ContactNote" (
contact_note_id SERIAL8 PRIMARY KEY,
contact_id INT8 NOT NULL,
contact_note_type_id INT NOT NULL,
user_id INT8 NOT NULL,
note TEXT NOT NULL,
note_datetime TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX "ContactNote_contact_id" ON "ContactNote" ("contact_id");
CREATE INDEX "ContactNote_contact_note_type_id" ON "ContactNote" ("contact_note_type_id");
CREATE TABLE "ContactNoteType" (
contact_note_type_id SERIAL PRIMARY KEY,
description TEXT NOT NULL,
is_system_defined BOOLEAN NOT NULL DEFAULT FALSE,
account_id INT8 NOT NULL,
CONSTRAINT valid_description CHECK ( description != '' ),
CONSTRAINT "ContactNoteType_description_account_id_unique"
UNIQUE ( description, account_id )
);
CREATE INDEX "ContactNoteType_account_id" ON "ContactNoteType" ("account_id");
CREATE TABLE "ContactHistory" (
contact_history_id SERIAL8 PRIMARY KEY,
contact_id INT8 NOT NULL,
contact_history_type_id INT NOT NULL,
user_id INT8 NOT NULL,
email_address_id INT8 NULL,
website_id INT8 NULL,
address_id INT8 NULL,
phone_number_id INT8 NULL,
other_contact_id INT8 NULL,
description TEXT NOT NULL DEFAULT '',
history_datetime TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- something that describes the change to the thing in question
-- as a data structure, and provides a way to reverse it,
-- presumably a Storable-created data structure
reversal_blob BYTEA NOT NULL,
CONSTRAINT contact_id_ne_other_contact_id CHECK ( contact_id != other_contact_id )
);
CREATE INDEX "ContactHistory_contact_id" ON "ContactHistory" ("contact_id");
CREATE INDEX "ContactHistory_contact_history_type_id"
ON "ContactHistory" ("contact_history_type_id");
CREATE INDEX "ContactHistory_user_id" ON "ContactHistory" ("user_id");
CREATE INDEX "ContactHistory_email_address_id" ON "ContactHistory" ("email_address_id");
CREATE INDEX "ContactHistory_website_id" ON "ContactHistory" ("website_id");
CREATE INDEX "ContactHistory_phone_number_id" ON "ContactHistory" ("phone_number_id");
CREATE INDEX "ContactHistory_other_contact_id" ON "ContactHistory" ("other_contact_id");
CREATE TABLE "ContactHistoryType" (
contact_history_type_id SERIAL PRIMARY KEY,
system_name TEXT UNIQUE NOT NULL,
description TEXT NOT NULL,
sort_order pos_int NOT NULL,
CONSTRAINT valid_description CHECK ( description != '' )
);
CREATE TABLE "ContactTag" (
contact_id INT8 NOT NULL,
tag_id INT8 NOT NULL,
PRIMARY KEY ( contact_id, tag_id )
);
CREATE INDEX "ContactTag_tag_id" ON "ContactTag" ("tag_id");
CREATE TABLE "Tag" (
tag_id SERIAL8 PRIMARY KEY,
tag citext NOT NULL,
account_id INT8 NOT NULL,
CONSTRAINT valid_tag CHECK ( tag != '' ),
CONSTRAINT "Tag_tag_account_id_unique" UNIQUE ( tag, account_id )
);
CREATE INDEX "Tag_account_id" ON "Tag" ("account_id");
-- An email list is simply additional data for a tag
CREATE TABLE "EmailList" (
tag_id INT8 PRIMARY KEY,
description TEXT NOT NULL
);
CREATE TABLE "ContactEmailListOptOut" (
tag_id INT8 NOT NULL,
contact_id INT8 NOT NULL,
PRIMARY KEY ( tag_id, contact_id )
);
CREATE INDEX "ContactEmailListOptOut_contact_id"
ON "ContactEmailListOptOut" ("contact_id");
CREATE TABLE "Activity" (
activity_id SERIAL8 PRIMARY KEY,
name citext NOT NULL,
activity_type_id INT8 NOT NULL,
creation_datetime TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
is_archived BOOLEAN DEFAULT FALSE,
account_id INT8 NOT NULL,
CONSTRAINT "Activity_account_id_name"
UNIQUE ( account_id, name )
);
CREATE TABLE "ActivityType" (
activity_type_id SERIAL8 PRIMARY KEY,
name TEXT NOT NULL,
display_order pos_int NOT NULL,
account_id INT8 NOT NULL,
CONSTRAINT valid_name CHECK ( name != '' ),
CONSTRAINT "ActivityType_account_id_name"
UNIQUE ( account_id, name ),
CONSTRAINT "ActivityType_account_id_display_order"
UNIQUE ( account_id, display_order )
);
CREATE TABLE "ContactParticipation" (
contact_participation_id SERIAL8 PRIMARY KEY,
contact_id INT8 NOT NULL,
activity_id INT8 NOT NULL,
participation_type_id INT8 NOT NULL,
description TEXT DEFAULT '',
start_date DATE NOT NULL,
end_date DATE NULL,
CONSTRAINT start_before_end
CHECK ( end_date IS NULL
OR end_date >= start_date )
);
CREATE TABLE "ParticipationType" (
participation_type_id SERIAL8 PRIMARY KEY,
name TEXT NOT NULL,
display_order pos_int NOT NULL,
account_id INT8 NOT NULL,
CONSTRAINT valid_name CHECK ( name != '' ),
CONSTRAINT "ParticipationType_account_id_name"
UNIQUE ( account_id, name ),
CONSTRAINT "ParticipationType_account_id_display_order"
UNIQUE ( account_id, display_order )
);
CREATE TABLE "Person" (
person_id INT8 PRIMARY KEY,
salutation citext NOT NULL DEFAULT '',
first_name citext NOT NULL DEFAULT '',
middle_name citext NOT NULL DEFAULT '',
last_name citext NOT NULL DEFAULT '',
suffix citext NOT NULL DEFAULT '',
birth_date DATE NULL,
gender citext NULL
);
CREATE TABLE "MessagingProvider" (
messaging_provider_id SERIAL8 PRIMARY KEY,
contact_id INT8 NOT NULL,
messaging_provider_type_id INT8 NOT NULL,
screen_name TEXT NOT NULL,
is_preferred BOOLEAN DEFAULT FALSE,
note TEXT NOT NULL DEFAULT ''
);
CREATE INDEX "MessagingProvider_contact_id" ON "MessagingProvider" ("contact_id");
CREATE INDEX "MessagingProvider_messaging_provider_type_id"
ON "MessagingProvider" ("messaging_provider_type_id");
CREATE TABLE "MessagingProviderType" (
messaging_provider_type_id SERIAL8 PRIMARY KEY,
name citext UNIQUE NOT NULL,
add_uri_template TEXT NOT NULL DEFAULT '',
chat_uri_template TEXT NOT NULL DEFAULT '',
call_uri_template TEXT NOT NULL DEFAULT '',
video_uri_template TEXT NOT NULL DEFAULT '',
status_uri_template TEXT NOT NULL DEFAULT ''
);
CREATE TABLE "PersonRelationship" (
person_id INT8 NOT NULL,
relationship_type_id INT8 NOT NULL,
other_person_id INT8 NOT NULL,
note TEXT NOT NULL DEFAULT '',
PRIMARY KEY ( person_id, relationship_type_id, other_person_id )
);
CREATE INDEX "PersonRelationship_relationship_type_id"
ON "PersonRelationship" ("relationship_type_id");
CREATE INDEX "PersonRelationship_other_person_id"
ON "PersonRelationship" ("other_person_id");
CREATE TABLE "RelationshipType" (
relationship_type_id SERIAL8 PRIMARY KEY,
account_id INT8 NOT NULL,
name TEXT NOT NULL,
inverse_name TEXT NOT NULL
);
CREATE INDEX "RelationshipType_account_id" ON "RelationshipType" ("account_id");
CREATE TABLE "Household" (
household_id SERIAL8 PRIMARY KEY,
name citext NOT NULL,
CONSTRAINT valid_name CHECK ( name != '' )
);
CREATE TABLE "HouseholdMember" (
household_id INT8 NOT NULL,
person_id INT8 NOT NULL,
position citext NOT NULL DEFAULT '',
creation_datetime TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ( household_id, person_id )
);
CREATE INDEX "HouseholdMember_person_id" ON "HouseholdMember" ("person_id");
CREATE TABLE "Organization" (
organization_id INT8 PRIMARY KEY,
name citext NOT NULL,
CONSTRAINT valid_name CHECK ( name != '' )
);
CREATE TABLE "OrganizationMember" (
organization_id INT8 NOT NULL,
person_id INT8 NOT NULL,
position citext NOT NULL DEFAULT '',
creation_datetime TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ( organization_id, person_id )
);
CREATE INDEX "OrganizationMember_person_id" ON "OrganizationMember" ("person_id");
-- It's tempting to make the email address unique, but contacts could
-- share an email address, especially in the case of a household and a
-- person in the household, or an organization.
CREATE TABLE "EmailAddress" (
email_address_id SERIAL8 PRIMARY KEY,
contact_id INT8 NOT NULL,
email_address email_address NOT NULL,
is_preferred BOOLEAN DEFAULT FALSE,
note TEXT NOT NULL DEFAULT ''
);
CREATE INDEX "EmailAddress_contact_id" ON "EmailAddress" ("contact_id");
CREATE TABLE "Website" (
website_id SERIAL8 PRIMARY KEY,
contact_id INT8 NOT NULL,
label TEXT NOT NULL DEFAULT 'Website',
uri uri NOT NULL,
note TEXT NOT NULL DEFAULT ''
);
CREATE INDEX "Website_contact_id" ON "Website" ("contact_id");
-- Consider a trigger to enforce one primary address per contact?
CREATE TABLE "Address" (
address_id SERIAL8 PRIMARY KEY,
contact_id INTEGER NOT NULL,
address_type_id INTEGER NOT NULL,
street_1 citext NOT NULL DEFAULT '',
street_2 citext NOT NULL DEFAULT '',
city citext NOT NULL DEFAULT '',
region citext NOT NULL DEFAULT '',
postal_code citext NOT NULL DEFAULT '',
country citext NOT NULL DEFAULT '',
latitude FLOAT NULL,
longitude FLOAT NULL,
-- The address as returned by a geocoding service like Google
-- Maps.
canonical_address TEXT NOT NULL DEFAULT '',
is_preferred BOOLEAN DEFAULT FALSE,
note TEXT NOT NULL DEFAULT '',
creation_datetime TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX "Address_contact_id" ON "Address" ("contact_id");
CREATE INDEX "Address_address_type_id" ON "Address" ("address_type_id");
CREATE TABLE "AddressType" (
address_type_id SERIAL8 PRIMARY KEY,
name TEXT NOT NULL,
display_order pos_int NOT NULL,
applies_to_person BOOLEAN NOT NULL DEFAULT FALSE,
applies_to_household BOOLEAN NOT NULL DEFAULT FALSE,
applies_to_organization BOOLEAN NOT NULL DEFAULT FALSE,
account_id INT8 NOT NULL,
CONSTRAINT valid_name CHECK ( name != '' ),
CONSTRAINT "AddressType_account_id_display_order_unique"
UNIQUE ( account_id, display_order )
);
CREATE INDEX "AddressType_account_id" ON "AddressType" ("account_id");
CREATE TABLE "TimeZone" (
olson_name TEXT PRIMARY KEY,
description VARCHAR(100) NOT NULL,
country citext NOT NULL,
display_order INTEGER NOT NULL,
CONSTRAINT valid_olson_name CHECK ( olson_name != '' ),
CONSTRAINT valid_description CHECK ( description != '' ),
CONSTRAINT valid_display_order CHECK ( display_order > 0 ),
CONSTRAINT TimeZone_country_display_order_unique
UNIQUE ( country, display_order )
);
-- Consider a trigger to enforce one primary phone number per contact?
CREATE TABLE "PhoneNumber" (
phone_number_id SERIAL8 PRIMARY KEY,
contact_id INTEGER NOT NULL,
phone_number_type_id INT8 NOT NULL,
phone_number TEXT DEFAULT '',
is_preferred BOOLEAN DEFAULT FALSE,
allows_sms BOOLEAN DEFAULT FALSE,
note TEXT NOT NULL DEFAULT '',
creation_datetime TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX "PhoneNumber_contact_id" ON "PhoneNumber" ("contact_id");
CREATE INDEX "PhoneNumber_phone_number_type_id"
ON "PhoneNumber" ("phone_number_type_id");
CREATE TABLE "PhoneNumberType" (
phone_number_type_id SERIAL8 PRIMARY KEY,
name TEXT NOT NULL,
display_order pos_int NOT NULL,
applies_to_person BOOLEAN NOT NULL DEFAULT FALSE,
applies_to_household BOOLEAN NOT NULL DEFAULT FALSE,
applies_to_organization BOOLEAN NOT NULL DEFAULT FALSE,
account_id INT8 NOT NULL,
CONSTRAINT valid_name CHECK ( name != '' ),
CONSTRAINT PhoneNumberType_account_id_display_order_unique
UNIQUE ( account_id, display_order )
);
CREATE INDEX "PhoneNumberType_account_id" ON "PhoneNumberType" ("account_id");
CREATE TABLE "Donation" (
donation_id SERIAL8 PRIMARY KEY,
amount NUMERIC(13,2) NOT NULL,
donation_date DATE NOT NULL,
contact_id INT8 NOT NULL,
gift_item TEXT NOT NULL DEFAULT '',
gift_sent_date DATE NULL,
value_for_donor NUMERIC(13,2) NOT NULL DEFAULT 0.00,
transaction_cost NUMERIC(13,2) NOT NULL DEFAULT 0.00,
dedication TEXT NOT NULL DEFAULT '',
recurrence_frequency TEXT NULL,
receipt_date DATE NULL,
donation_source_id INT8 NOT NULL,
donation_campaign_id INT8 NOT NULL,
payment_type_id INT8 NOT NULL,
external_id TEXT NULL,
note TEXT NOT NULL DEFAULT '',
CONSTRAINT valid_amount CHECK ( amount > 0.00 ),
CONSTRAINT valid_value_for_donor CHECK ( value_for_donor >= 0.00 ),
CONSTRAINT valid_transaction_cost CHECK ( transaction_cost >= 0.00 )
);
CREATE INDEX "Donation_contact_id" ON "Donation" ("contact_id");
CREATE INDEX "Donation_donation_source_id" ON "Donation" ("donation_source_id");
CREATE INDEX "Donation_donation_campaign_id" ON "Donation" ("donation_campaign_id");
CREATE INDEX "Donation_payment_type_id" ON "Donation" ("payment_type_id");
CREATE TABLE "DonationSource" (
donation_source_id SERIAL8 PRIMARY KEY,
name TEXT NOT NULL,
display_order pos_int NOT NULL,
account_id INT8 NOT NULL,
is_active BOOLEAN DEFAULT TRUE,
CONSTRAINT valid_name CHECK ( name != '' ),
CONSTRAINT DonationSource_account_id_display_order_unique
UNIQUE ( account_id, display_order )
);
CREATE INDEX "DonationSource_account_id" ON "DonationSource" ("account_id");
CREATE TABLE "DonationCampaign" (
donation_campaign_id SERIAL8 PRIMARY KEY,
name TEXT NOT NULL,
display_order pos_int NOT NULL,
account_id INT8 NOT NULL,
is_active BOOLEAN DEFAULT TRUE,
CONSTRAINT valid_name CHECK ( name != '' ),
CONSTRAINT DonationCampaign_account_id_display_order_unique
UNIQUE ( account_id, display_order )
);
CREATE INDEX "DonationCampaign_account_id" ON "DonationCampaign" ("account_id");
CREATE TABLE "PaymentType" (
payment_type_id SERIAL8 PRIMARY KEY,
name TEXT NOT NULL,
display_order pos_int NOT NULL,
account_id INT8 NOT NULL,
is_active BOOLEAN DEFAULT TRUE,
CONSTRAINT valid_name CHECK ( name != '' ),
CONSTRAINT PaymentType_account_id_display_order_unique
UNIQUE ( account_id, display_order )
);
CREATE INDEX "PaymentType_account_id" ON "PaymentType" ("account_id");
CREATE TABLE "SavedSearch" (
name TEXT NOT NULL,
class TEXT NOT NULL,
params TEXT NOT NULL,
user_id INT8 NOT NULL,
is_shared BOOLEAN DEFAULT FALSE,
CONSTRAINT valid_name CHECK ( name != '' ),
CONSTRAINT valid_class CHECK ( class != '' ),
PRIMARY KEY ( name, user_id )
);
CREATE TABLE "Session" (
id CHAR(72) PRIMARY KEY,
session_data BYTEA NOT NULL,
expires INT NOT NULL
);
ALTER TABLE "User" ADD CONSTRAINT "User_person_id"
FOREIGN KEY ("person_id") REFERENCES "Person" ("person_id")
ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "User" ADD CONSTRAINT "User_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "User" ADD CONSTRAINT "User_role_id"
FOREIGN KEY ("role_id") REFERENCES "Role" ("role_id")
ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "Account" ADD CONSTRAINT "Account_domain_id"
FOREIGN KEY ("domain_id") REFERENCES "Domain" ("domain_id")
ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "File" ADD CONSTRAINT "File_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Contact" ADD CONSTRAINT "Contact_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Contact" ADD CONSTRAINT "Contact_image_file_id"
FOREIGN KEY ("image_file_id") REFERENCES "File" ("file_id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "CustomFieldGroup" ADD CONSTRAINT "CustomFieldGroup_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomField" ADD CONSTRAINT "CustomField_custom_field_group_id"
FOREIGN KEY ("custom_field_group_id") REFERENCES "CustomFieldGroup" ("custom_field_group_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomField" ADD CONSTRAINT "CustomField_html_widget_id"
FOREIGN KEY ("html_widget_id") REFERENCES "HTMLWidget" ("html_widget_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldIntegerValue" ADD CONSTRAINT "CustomFieldIntegerValue_custom_field_id"
FOREIGN KEY ("custom_field_id") REFERENCES "CustomField" ("custom_field_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldIntegerValue" ADD CONSTRAINT "CustomFieldIntegerValue_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldDecimalValue" ADD CONSTRAINT "CustomFieldDecimalValue_custom_field_id"
FOREIGN KEY ("custom_field_id") REFERENCES "CustomField" ("custom_field_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldDecimalValue" ADD CONSTRAINT "CustomFieldDecimalValue_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldDateValue" ADD CONSTRAINT "CustomFieldDateValue_custom_field_id"
FOREIGN KEY ("custom_field_id") REFERENCES "CustomField" ("custom_field_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldDateValue" ADD CONSTRAINT "CustomFieldDateValue_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldDateTimeValue" ADD CONSTRAINT "CustomFieldDateTimeValue_custom_field_id"
FOREIGN KEY ("custom_field_id") REFERENCES "CustomField" ("custom_field_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldDateTimeValue" ADD CONSTRAINT "CustomFieldDateTimeValue_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldTextValue" ADD CONSTRAINT "CustomFieldTextValue_custom_field_id"
FOREIGN KEY ("custom_field_id") REFERENCES "CustomField" ("custom_field_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldTextValue" ADD CONSTRAINT "CustomFieldTextValue_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldFileValue" ADD CONSTRAINT "CustomFieldFileValue_custom_field_id"
FOREIGN KEY ("custom_field_id") REFERENCES "CustomField" ("custom_field_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldFileValue" ADD CONSTRAINT "CustomFieldFileValue_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldSelectOption" ADD CONSTRAINT "CustomFieldSelectOption_custom_field_id"
FOREIGN KEY ("custom_field_id") REFERENCES "CustomField" ("custom_field_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldSingleSelectValue" ADD CONSTRAINT "CustomFieldSingleSelectValue_custom_field_id"
FOREIGN KEY ("custom_field_id") REFERENCES "CustomField" ("custom_field_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldSingleSelectValue" ADD CONSTRAINT "CustomFieldSingleSelectValue_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldSingleSelectValue" ADD CONSTRAINT "CustomFieldSingleSelectValue_custom_field_select_option_id"
FOREIGN KEY ("custom_field_select_option_id") REFERENCES "CustomFieldSelectOption" ("custom_field_select_option_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldMultiSelectValue" ADD CONSTRAINT "CustomFieldMultiSelectValue_custom_field_id"
FOREIGN KEY ("custom_field_id") REFERENCES "CustomField" ("custom_field_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldMultiSelectValue" ADD CONSTRAINT "CustomFieldMultiSelectValue_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "CustomFieldMultiSelectValue" ADD CONSTRAINT "CustomFieldMultiSelectValue_custom_field_select_option_id"
FOREIGN KEY ("custom_field_select_option_id") REFERENCES "CustomFieldSelectOption" ("custom_field_select_option_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "ContactHistory" ADD CONSTRAINT "ContactHistory_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "ContactHistory" ADD CONSTRAINT "ContactHistory_user_id"
FOREIGN KEY ("user_id") REFERENCES "User" ("user_id")
ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "ContactHistory" ADD CONSTRAINT "ContactHistory_contact_history_type_id"
FOREIGN KEY ("contact_history_type_id") REFERENCES "ContactHistoryType" ("contact_history_type_id")
ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "ContactHistory" ADD CONSTRAINT "ContactHistory_email_address_id"
FOREIGN KEY ("email_address_id") REFERENCES "EmailAddress" ("email_address_id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "ContactHistory" ADD CONSTRAINT "ContactHistory_website_id"
FOREIGN KEY ("website_id") REFERENCES "Website" ("website_id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "ContactHistory" ADD CONSTRAINT "ContactHistory_address_id"
FOREIGN KEY ("address_id") REFERENCES "Address" ("address_id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "ContactHistory" ADD CONSTRAINT "ContactHistory_phone_number_id"
FOREIGN KEY ("phone_number_id") REFERENCES "PhoneNumber" ("phone_number_id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "ContactHistory" ADD CONSTRAINT "ContactHistory_other_contact_id"
FOREIGN KEY ("other_contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "Email" ADD CONSTRAINT "Email_from_contact_id"
FOREIGN KEY ("from_contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "Email" ADD CONSTRAINT "Email_from_user_id"
FOREIGN KEY ("from_user_id") REFERENCES "User" ("user_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Email" ADD CONSTRAINT "Email_donation_id"
FOREIGN KEY ("donation_id") REFERENCES "Donation" ("donation_id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "Email" ADD CONSTRAINT "Email_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "ContactEmail" ADD CONSTRAINT "ContactEmail_email_id"
FOREIGN KEY ("email_id") REFERENCES "Email" ("email_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "ContactEmail" ADD CONSTRAINT "ContactEmail_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "ContactNote" ADD CONSTRAINT "ContactNote_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "ContactNote" ADD CONSTRAINT "ContactNote_user_id"
FOREIGN KEY ("user_id") REFERENCES "User" ("user_id")
ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "ContactNote" ADD CONSTRAINT "ContactNote_contact_note_type_id"
FOREIGN KEY ("contact_note_type_id") REFERENCES "ContactNoteType" ("contact_note_type_id")
ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "ContactNoteType" ADD CONSTRAINT "ContactNoteType_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "ContactTag" ADD CONSTRAINT "ContactTag_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "ContactTag" ADD CONSTRAINT "ContactTag_tag_id"
FOREIGN KEY ("tag_id") REFERENCES "Tag" ("tag_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Tag" ADD CONSTRAINT "Account_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "EmailList" ADD CONSTRAINT "Tag_tag_id"
FOREIGN KEY ("tag_id") REFERENCES "Tag" ("tag_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "ContactEmailListOptOut" ADD CONSTRAINT "Tag_tag_id"
FOREIGN KEY ("tag_id") REFERENCES "Tag" ("tag_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "ContactEmailListOptOut" ADD CONSTRAINT "Contact_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_activity_type_id"
FOREIGN KEY ("activity_type_id") REFERENCES "ActivityType" ("activity_type_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "ActivityType" ADD CONSTRAINT "ActivityType_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "ContactParticipation" ADD CONSTRAINT "ContactParticipation_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "ContactParticipation" ADD CONSTRAINT "ContactParticipation_activity_id"
FOREIGN KEY ("activity_id") REFERENCES "Activity" ("activity_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "ContactParticipation" ADD CONSTRAINT "ContactParticipation_participation_type_id"
FOREIGN KEY ("participation_type_id") REFERENCES "ParticipationType" ("participation_type_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "ParticipationType" ADD CONSTRAINT "ParticipationType_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Person" ADD CONSTRAINT "Person_person_id"
FOREIGN KEY ("person_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "MessagingProvider" ADD CONSTRAINT "MessagingProvider_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "MessagingProvider" ADD CONSTRAINT "MessagingProvider_messaging_provider_type_id"
FOREIGN KEY ("messaging_provider_type_id") REFERENCES "MessagingProviderType" ("messaging_provider_type_id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "PersonRelationship" ADD CONSTRAINT "PersonRelationship_person_id"
FOREIGN KEY ("person_id") REFERENCES "Person" ("person_id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "PersonRelationship" ADD CONSTRAINT "PersonRelationship_relationship_type_id"
FOREIGN KEY ("relationship_type_id") REFERENCES "RelationshipType" ("relationship_type_id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "PersonRelationship" ADD CONSTRAINT "PersonRelationship_other_person_id"
FOREIGN KEY ("other_person_id") REFERENCES "Person" ("person_id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "RelationshipType" ADD CONSTRAINT "RelationshipType_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Household" ADD CONSTRAINT "Household_household_id"
FOREIGN KEY ("household_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "HouseholdMember" ADD CONSTRAINT "HouseholdMember_household_id"
FOREIGN KEY ("household_id") REFERENCES "Household" ("household_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "HouseholdMember" ADD CONSTRAINT "HouseholdMember_person_id"
FOREIGN KEY ("person_id") REFERENCES "Person" ("person_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Organization" ADD CONSTRAINT "Organization_organization_id"
FOREIGN KEY ("organization_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "OrganizationMember" ADD CONSTRAINT "OrganizationMember_organization_id"
FOREIGN KEY ("organization_id") REFERENCES "Organization" ("organization_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "OrganizationMember" ADD CONSTRAINT "OrganizationMember_person_id"
FOREIGN KEY ("person_id") REFERENCES "Person" ("person_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "EmailAddress" ADD CONSTRAINT "EmailAddress_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Address" ADD CONSTRAINT "Address_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Address" ADD CONSTRAINT "Address_address_type_id"
FOREIGN KEY ("address_type_id") REFERENCES "AddressType" ("address_type_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "AddressType" ADD CONSTRAINT "AddressType_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "PhoneNumber" ADD CONSTRAINT "PhoneNumber_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "PhoneNumber" ADD CONSTRAINT "PhoneNumber_phone_number_type_id"
FOREIGN KEY ("phone_number_type_id") REFERENCES "PhoneNumberType" ("phone_number_type_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "PhoneNumberType" ADD CONSTRAINT "PhoneNumberType_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Website" ADD CONSTRAINT "Website_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Donation" ADD CONSTRAINT "Donation_contact_id"
FOREIGN KEY ("contact_id") REFERENCES "Contact" ("contact_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Donation" ADD CONSTRAINT "Donation_donation_source_id"
FOREIGN KEY ("donation_source_id") REFERENCES "DonationSource" ("donation_source_id")
ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "DonationSource" ADD CONSTRAINT "DonationSource_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Donation" ADD CONSTRAINT "Donation_donation_campaign_id"
FOREIGN KEY ("donation_campaign_id") REFERENCES "DonationCampaign" ("donation_campaign_id")
ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "Donation" ADD CONSTRAINT "Donation_payment_type_id"
FOREIGN KEY ("payment_type_id") REFERENCES "PaymentType" ("payment_type_id")
ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "DonationCampaign" ADD CONSTRAINT "DonationCampaign_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "PaymentType" ADD CONSTRAINT "PaymentType_account_id"
FOREIGN KEY ("account_id") REFERENCES "Account" ("account_id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "SavedSearch" ADD CONSTRAINT "SavedSearch_user_id"
FOREIGN KEY ("user_id") REFERENCES "User" ("user_id")
ON DELETE CASCADE ON UPDATE CASCADE;
INSERT INTO "Version" (version) VALUES (1);
|
INSERT INTO Chess_Player(id, birth_date, first_name, last_name, version) VALUES (1, '1990-09-30', 'Magnus', 'Carlsen', 0);
INSERT INTO Chess_Player(id, birth_date, first_name, last_name, version) VALUES (2, '1999-04-30', 'Jorden', 'van Foreest', 0);
INSERT INTO Chess_Player(id, birth_date, first_name, last_name, version) VALUES (3, '1994-06-28', 'Anish', 'Giri', 0);
INSERT INTO Chess_Player(id, birth_date, first_name, last_name, version) VALUES (4, '1992-07-30', 'Fabiano', 'Caruana', 0);
INSERT INTO Chess_Player(id, first_name, last_name, version) VALUES (20, 'John', 'Doe', 0);
INSERT INTO Chess_Player(id, first_name, last_name, version) VALUES (21, 'John', 'Doe', 0);
INSERT INTO Chess_Player(id, first_name, last_name, version) VALUES (22, 'John', 'Doe', 0);
INSERT INTO Chess_Player(id, first_name, last_name, version) VALUES (23, 'John', 'Doe', 0);
INSERT INTO Chess_Player(id, first_name, last_name, version) VALUES (24, 'John', 'Doe', 0);
INSERT INTO Chess_Player(id, first_name, last_name, version) VALUES (25, 'John', 'Doe', 0);
INSERT INTO Chess_Player(id, first_name, last_name, version) VALUES (26, 'John', 'Doe', 0);
INSERT INTO Chess_Player(id, first_name, last_name, version) VALUES (27, 'John', 'Doe', 0);
INSERT INTO Chess_Player(id, first_name, last_name, version) VALUES (28, 'John', 'Doe', 0);
INSERT INTO Chess_Player(id, first_name, last_name, version) VALUES (29, 'John', 'Doe', 0);
INSERT INTO Chess_Player(id, first_name, last_name, version) VALUES (30, 'John', 'Doe', 0);
INSERT INTO Chess_Player(id, first_name, last_name, version) VALUES (31, 'John', 'Doe', 0);
INSERT INTO Chess_Player(id, first_name, last_name, version) VALUES (32, 'John', 'Doe', 0);
INSERT INTO Chess_Player(id, first_name, last_name, version) VALUES (33, 'John', 'Doe', 0);
INSERT INTO Chess_Player(id, first_name, last_name, version) VALUES (34, 'John', 'Doe', 0);
INSERT INTO Chess_Tournament(id, start_date, end_date, name, version) VALUES (1, '2021-01-14', '2021-01-30', 'Tata Steel Chess Tournament 2021', 0);
INSERT INTO Chess_Tournament(id, start_date, end_date, name, version) VALUES (2, '2021-05-22', '2021-05-25', 'Local Championship', 0);
INSERT INTO Chess_Game(id, round, version, chess_tournament_id, player_white_id, player_black_id) VALUES (1, 4, 0, 1, 2, 1);
INSERT INTO Chess_Game(id, round, version, chess_tournament_id, player_white_id, player_black_id) VALUES (2, 10, 0, 1, 4, 1);
INSERT INTO Chess_Game(id, round, version, chess_tournament_id, player_white_id, player_black_id) VALUES (3, 11, 0, 1, 1, 3);
INSERT INTO Chess_Game(id, round, version, chess_tournament_id, player_white_id, player_black_id) VALUES (4, 2, 0, 1, 2, 3);
INSERT INTO Chess_Game(id, round, version, chess_tournament_id, player_white_id, player_black_id) VALUES (5, 1, 0, 1, 4, 2);
INSERT INTO Chess_Game(id, round, version, chess_tournament_id, player_white_id, player_black_id) VALUES (6, 8, 0, 1, 4, 3);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (1, 1);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (1, 2);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (1, 3);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (1, 4);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (2, 20);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (2, 21);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (2, 22);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (2, 23);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (2, 24);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (2, 25);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (2, 26);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (2, 27);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (2, 28);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (2, 29);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (2, 30);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (2, 31);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (2, 32);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (2, 33);
INSERT INTO Chess_Tournament_Players(tournaments_id, players_id) VALUES (2, 34); |
--Нужно вывести 5 команд (shortName + shortName из team_info.csv)
--в которых номинальные защитники (primaryPosition = "D" из player_info.csv)
--забили (goals из game_skater_stats.csv) наибольший процент голов
--(метрика (голы, забитые защитниками) / (голы, забитые всей командой) максимальное).
--Команды должны быть отсортированы в порядке убывания метрики.
SELECT short_name, team_name,
(
SELECT SUM(goals)
FROM game_skater_stats
WHERE team_id = team_info.team_id AND
(
SELECT primary_position
FROM player_info
WHERE player_id = game_skater_stats.player_id
) = 'D'
)/(
SELECT SUM(goals)
FROM game_skater_stats
WHERE team_id = team_info.team_id
) AS METRIC
FROM team_info
ORDER BY METRIC DESC NULLS LAST
limit 5;
|
select @@TX_ISOLATION;
set session transaction isolation level read uncommitted;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SELECT @@TX_ISOLATION;
SET AUTOCOMMIT=1;
SELECT @@AUTOCOMMIT
show variables like 'autocommit';
CREATE TABLE `users` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
--------
INSERT INTO `countries` (`country_id`,`country_name`) VALUES ('1','TURKIYE');
INSERT INTO `countries` (`country_id`,`country_name`) VALUES ('2','ESTONIA');
--------
INSERT INTO `provinces` (`province_id`,`province_name`,`country_country_id`) VALUES ('1','ADANA','1');
INSERT INTO `provinces` (`province_id`,`province_name`,`country_country_id`) VALUES ('2','ANKARA','1');
--------
INSERT INTO `universities` (`uni_id`, `uni_name`,`uni_country_country_id`,`uni_province_province_id`) VALUES ('1', 'YILDIRIM BEYAZIT UNIVERSITESI','1','2');
INSERT INTO `universities` (`uni_id`, `uni_name`,`uni_country_country_id`,`uni_province_province_id`) VALUES ('2', 'ODTU','1','2');
--------
INSERT INTO `organizations` (`org_id`,`org_name`,`org_detail`) VALUES ('1','BCYCLE LOVERS','BCYCLE IS LIFE');
INSERT INTO `organizations` (`org_id`,`org_name`,`org_detail`) VALUES ('2','BOOK LOVERS','BOOK IS PART OF LIFE');
--------
INSERT INTO `role` (`role_id`,`role`) VALUES ('1','ADMIN');
INSERT INTO `role` (`role_id`,`role`) VALUES ('2','ORGADMIN');
INSERT INTO `role` (`role_id`,`role`) VALUES ('3','UNIREP');
INSERT INTO `role` (`role_id`,`role`) VALUES ('4','USER');
|
create table pessoa(
codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT,
nome VARCHAR(50) NOT NULL,
ativo BOOL NOT NULL,
logadouro VARCHAR(50),
numero VARCHAR(50),
complemento VARCHAR(50),
bairro VARCHAR(50),
cep VARCHAR(50),
cidade VARCHAR(50),
estado VARCHAR(50)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO pessoa (nome, ativo, logadouro, numero, complemento, bairro, cep, cidade, estado) VALUES ('Lucas Jeronimo', true, 'SP', '125', 'Casa', 'Centro', '15787878', 'Riberão Preto', 'São Paulo');
INSERT INTO pessoa (nome, ativo, logadouro, numero, complemento, bairro, cep, cidade, estado) VALUES ('Angelica', true, 'SP', '125', 'Casa', 'Centro', '15787878', 'Riberão Preto', 'São Paulo');
INSERT INTO pessoa (nome, ativo, logadouro, numero, complemento, bairro, cep, cidade, estado) VALUES ('FAved', false, 'RJ', '125', 'Casa da Sogra', 'Favela', '15787878', 'Rio de Janeiro', 'Rio de Janeiro');
INSERT INTO pessoa (nome, ativo, logadouro, numero, complemento, bairro, cep, cidade, estado) VALUES ('kado', false, 'SP', '125', 'Casa', 'Centro', '15787878', 'Riberão Preto', 'São Paulo');
INSERT INTO pessoa (nome, ativo, logadouro, numero, complemento, bairro, cep, cidade, estado) VALUES ('Luck',true, 'SP', '125', 'Casa', 'Centro', '15787878', 'Riberão Preto', 'São Paulo');
INSERT INTO pessoa (nome, ativo, logadouro, numero, complemento, bairro, cep, cidade, estado) VALUES ('NAta', false, 'SP', '125', 'Casa', 'Centro', '15787878', 'Riberão Preto', 'São Paulo');
|
-- MySQL Script generated by MySQL Workbench
-- Sat Jun 3 12:20:44 2017
-- 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 show_do_milhao
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema show_do_milhao
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `show_do_milhao` DEFAULT CHARACTER SET utf8 ;
USE `show_do_milhao` ;
-- -----------------------------------------------------
-- Table `show_do_milhao`.`Jogador`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `show_do_milhao`.`Jogador` (
`idJogador` INT NOT NULL AUTO_INCREMENT,
`Email` VARCHAR(150) NOT NULL,
`Nome` VARCHAR(200) NOT NULL,
`Instituicao` VARCHAR(150) NOT NULL,
`Equipe` VARCHAR(100) NULL,
`CPF` VARCHAR(14) NOT NULL,
`Senha` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idJogador`, `Email`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `show_do_milhao`.`Curso`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `show_do_milhao`.`Curso` (
`idCurso` INT NOT NULL AUTO_INCREMENT,
`Descricao_Curso` VARCHAR(150) NOT NULL,
`Grande_Area` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idCurso`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `show_do_milhao`.`Professor`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `show_do_milhao`.`Professor` (
`idProfessor` INT NOT NULL AUTO_INCREMENT,
`Email` VARCHAR(150) NOT NULL,
`Nome` VARCHAR(200) NOT NULL,
`CPF` VARCHAR(14) NOT NULL,
`Curriculo` VARCHAR(150) NOT NULL,
`Instituicao` VARCHAR(150) NOT NULL,
`Titulacao` VARCHAR(150) NOT NULL,
`Senha` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idProfessor`, `Email`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `show_do_milhao`.`Jogo`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `show_do_milhao`.`Jogo` (
`idJogo` INT NOT NULL AUTO_INCREMENT,
`Descricao_Jogo` VARCHAR(45) NOT NULL,
`Visibilidade_Jogo` VARCHAR(45) NOT NULL,
`Curso_idCurso` INT NOT NULL,
`Professor_idProfessor` INT NOT NULL,
PRIMARY KEY (`idJogo`, `Curso_idCurso`, `Professor_idProfessor`, `Descricao_Jogo`),
INDEX `fk_Jogo_Curso1_idx` (`Curso_idCurso` ASC),
INDEX `fk_Jogo_Professor1_idx` (`Professor_idProfessor` ASC),
CONSTRAINT `fk_Jogo_Curso1`
FOREIGN KEY (`Curso_idCurso`)
REFERENCES `show_do_milhao`.`Curso` (`idCurso`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Jogo_Professor1`
FOREIGN KEY (`Professor_idProfessor`)
REFERENCES `show_do_milhao`.`Professor` (`idProfessor`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `show_do_milhao`.`Partida`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `show_do_milhao`.`Partida` (
`idPartida` INT NOT NULL AUTO_INCREMENT,
`Data` DATE NOT NULL,
`Hora` TIME NOT NULL,
`Duracao` INT NOT NULL,
`Pontuacao` FLOAT NOT NULL,
`VisibilidadeAluno` INT UNSIGNED NOT NULL,
`Jogador_idJogador` INT NOT NULL,
`Jogo_idJogo` INT NOT NULL,
`Jogo_Curso_idCurso` INT NOT NULL,
`Partidacol` INT NOT NULL,
PRIMARY KEY (`idPartida`, `Jogador_idJogador`, `Jogo_idJogo`, `Jogo_Curso_idCurso`, `Partidacol`),
INDEX `fk_Partida_Jogador1_idx` (`Jogador_idJogador` ASC),
INDEX `fk_Partida_Jogo1_idx` (`Jogo_idJogo` ASC, `Jogo_Curso_idCurso` ASC, `Partidacol` ASC),
CONSTRAINT `fk_Partida_Jogador1`
FOREIGN KEY (`Jogador_idJogador`)
REFERENCES `show_do_milhao`.`Jogador` (`idJogador`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Partida_Jogo1`
FOREIGN KEY (`Jogo_idJogo` , `Jogo_Curso_idCurso` , `Partidacol`)
REFERENCES `show_do_milhao`.`Jogo` (`idJogo` , `Curso_idCurso` , `Professor_idProfessor`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `show_do_milhao`.`Perguntas`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `show_do_milhao`.`Perguntas` (
`idPerguntas` INT NOT NULL AUTO_INCREMENT,
`Enunciado` VARCHAR(200) NOT NULL,
`RespostaCorreta` VARCHAR(200) NOT NULL,
`Alternativa_1` VARCHAR(45) NOT NULL,
`Alternativa_2` VARCHAR(45) NOT NULL,
`Alternativa_3` VARCHAR(45) NOT NULL,
`Alternativa_4` VARCHAR(45) NOT NULL,
`Alternativa_5` VARCHAR(45) NOT NULL,
`Jogo_idJogo` INT NOT NULL,
PRIMARY KEY (`idPerguntas`, `Jogo_idJogo`),
INDEX `fk_Perguntas_Jogo1_idx` (`Jogo_idJogo` ASC),
CONSTRAINT `fk_Perguntas_Jogo1`
FOREIGN KEY (`Jogo_idJogo`)
REFERENCES `show_do_milhao`.`Jogo` (`idJogo`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `show_do_milhao`.`Disciplina`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `show_do_milhao`.`Disciplina` (
`idDisciplina` INT NOT NULL AUTO_INCREMENT,
`Descricao_Disciplina` VARCHAR(150) NOT NULL,
`Curso_idCurso` INT NOT NULL,
PRIMARY KEY (`idDisciplina`, `Curso_idCurso`),
INDEX `fk_Disciplina_Curso1_idx` (`Curso_idCurso` ASC),
CONSTRAINT `fk_Disciplina_Curso1`
FOREIGN KEY (`Curso_idCurso`)
REFERENCES `show_do_milhao`.`Curso` (`idCurso`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `show_do_milhao`.`Assunto`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `show_do_milhao`.`Assunto` (
`idAssunto` INT NOT NULL AUTO_INCREMENT,
`Descricao_Assunto` VARCHAR(150) NOT NULL,
`Disciplina_idDisciplina` INT NOT NULL,
`Disciplina_Curso_idCurso` INT NOT NULL,
PRIMARY KEY (`idAssunto`, `Disciplina_idDisciplina`, `Disciplina_Curso_idCurso`),
INDEX `fk_Assunto_Disciplina1_idx` (`Disciplina_idDisciplina` ASC, `Disciplina_Curso_idCurso` ASC),
CONSTRAINT `fk_Assunto_Disciplina1`
FOREIGN KEY (`Disciplina_idDisciplina` , `Disciplina_Curso_idCurso`)
REFERENCES `show_do_milhao`.`Disciplina` (`idDisciplina` , `Curso_idCurso`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `show_do_milhao`.`Acesso`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `show_do_milhao`.`Acesso` (
`idAcesso` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`Status_Acesso` VARCHAR(45) NOT NULL,
`Jogador_idJogador` INT NOT NULL,
`Jogador_Email` VARCHAR(150) NOT NULL,
`Jogo_idJogo` INT NOT NULL,
`Jogo_Curso_idCurso` INT NOT NULL,
`Jogo_Professor_idProfessor` INT NOT NULL,
`Jogo_Descricao_Jogo` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idAcesso`, `Jogador_idJogador`, `Jogador_Email`, `Jogo_idJogo`, `Jogo_Curso_idCurso`, `Jogo_Professor_idProfessor`, `Jogo_Descricao_Jogo`),
INDEX `fk_Acesso_Jogador1_idx` (`Jogador_idJogador` ASC, `Jogador_Email` ASC),
INDEX `fk_Acesso_Jogo1_idx` (`Jogo_idJogo` ASC, `Jogo_Curso_idCurso` ASC, `Jogo_Professor_idProfessor` ASC, `Jogo_Descricao_Jogo` ASC),
CONSTRAINT `fk_Acesso_Jogador1`
FOREIGN KEY (`Jogador_idJogador` , `Jogador_Email`)
REFERENCES `show_do_milhao`.`Jogador` (`idJogador` , `Email`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Acesso_Jogo1`
FOREIGN KEY (`Jogo_idJogo` , `Jogo_Curso_idCurso` , `Jogo_Professor_idProfessor` , `Jogo_Descricao_Jogo`)
REFERENCES `show_do_milhao`.`Jogo` (`idJogo` , `Curso_idCurso` , `Professor_idProfessor` , `Descricao_Jogo`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
|
SELECT
`last_name`,
`first_name`
FROM
`db_pgritsen`.`user_card`
WHERE
`last_name` LIKE '%-%' OR `first_name` LIKE '%-%'
ORDER BY
`last_name` ASC,
`first_name` ASC; |
UPDATE employees SET firstname="sasi", lastname="",age="" WHERE id=""; |
--Interrogação 4: Quais os filmes que ainda não venderam bilhetes?
.mode columns
.headers on
.nullvalue NULL
SELECT DISTINCT nome
FROM Filme
WHERE idFilme NOT IN
(SELECT idFilme
FROM Bilhete, Sessao
WHERE Bilhete.idSessao = Sessao.idSessao);
|
-- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 01-03-2018 a las 20:43:51
-- Versión del servidor: 10.1.30-MariaDB
-- Versión de PHP: 7.2.1
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: `proyecto`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `archivo`
--
CREATE TABLE `archivo` (
`id` int(11) NOT NULL,
`user_id` int(10) UNSIGNED NOT NULL,
`titulo` varchar(254) COLLATE utf8_spanish_ci NOT NULL,
`descripcion` longtext COLLATE utf8_spanish_ci NOT NULL,
`imagen` varchar(255) COLLATE utf8_spanish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `users`
--
CREATE TABLE `users` (
`id` int(10) UNSIGNED NOT NULL,
`username` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`token` varchar(255) NOT NULL,
`direccion` varchar(255) NOT NULL,
`codigo_postal` int(11) NOT NULL,
`telefono` int(255) NOT NULL,
`creado` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`actualizado` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Volcado de datos para la tabla `users`
--
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `archivo`
--
ALTER TABLE `archivo`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `imagen` (`imagen`),
ADD KEY `user_id` (`user_id`),
ADD KEY `user_id_2` (`user_id`);
--
-- Indices de la tabla `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `token` (`token`),
ADD UNIQUE KEY `email` (`email`),
ADD UNIQUE KEY `username` (`username`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `archivo`
--
ALTER TABLE `archivo`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `users`
--
ALTER TABLE `users`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=29;
--
-- Restricciones para tablas volcadas
--
--
-- Filtros para la tabla `archivo`
--
ALTER TABLE `archivo`
ADD CONSTRAINT `archivo_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
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 */;
|
-- script that lists all the tables
-- of a database in your MySQL server.
SHOW TABLES
|
DROP TABLE IF EXISTS city;
CREATE TABLE IF NOT EXISTS cities (
gid BIGINT UNSIGNED NOT NULL UNIQUE,
data MEDIUMBLOB NOT NULL
)
CHARACTER SET = utf8
ENGINE = InnoDB;
DELIMITER $$
DROP PROCEDURE IF EXISTS add_city$$
CREATE PROCEDURE add_city (IN param1 BIGINT UNSIGNED, IN param2 MEDIUMBLOB)
BEGIN
INSERT INTO cities(gid, data)
VALUES(param1, param2);
END$$
DROP PROCEDURE IF EXISTS find_city$$
CREATE PROCEDURE find_city (IN param1 BIGINT UNSIGNED)
BEGIN
SELECT data
FROM cities
WHERE gid = param1;
END$$
DROP PROCEDURE IF EXISTS update_city$$
CREATE PROCEDURE update_city (IN param1 BIGINT UNSIGNED, IN param2 MEDIUMBLOB)
BEGIN
UPDATE cities
SET data = param2
WHERE gid = param1;
END$$
DROP PROCEDURE IF EXISTS get_cities$$
CREATE PROCEDURE get_cities ()
BEGIN
SELECT gid, data
FROM cities;
END$$
|
-- MySQL dump 10.13 Distrib 5.6.26, for Win32 (x86)
--
-- Host: localhost Database: blog
-- ------------------------------------------------------
-- Server version 5.6.26-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 `users`
--
DROP TABLE IF EXISTS `roles`;
CREATE TABLE `roles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rolename` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
--
-- Insert default role
--
INSERT INTO roles (rolename) VALUES('Admin');
--
-- Table structure for table `users`
--
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
`status` int(1) DEFAULT 1 NOT NULL,
`roleId` int(11) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT user_role FOREIGN KEY (roleId) REFERENCES roles(id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
--
-- Insert default user
--
INSERT INTO users(username,password,email,status,roleId) VALUES('admin','admin123','admin@xyz.com',1,1);
--
-- Table structure for table `categories`
--
DROP TABLE IF EXISTS `categories`;
CREATE TABLE `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`catname` varchar(100) NOT NULL,
`catId` int(11) DEFAULT NULL,
`level` int(2) DEFAULT 0 NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
--
-- Table structure for table `blogs`
--
DROP TABLE IF EXISTS `blogs`;
CREATE TABLE `blogs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(200) NOT NULL,
`intro` text NOT NULL,
`thumnailImg` varchar(200) DEFAULT NULL,
`content` text NOT NULL,
`date` datetime NOT NULL,
`catId` int(11) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT cat_blog FOREIGN KEY (catId) REFERENCES categories (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
--
-- Table structure for table `comments`
--
DROP TABLE IF EXISTS `comments`;
CREATE TABLE `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`comment` varchar(500) NOT NULL,
`blogId` int(11) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT blog_comment FOREIGN KEY (blogId) REFERENCES blogs(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `comment`
--
|
UPDATE Languages
Set rating = 5 |
/*
Navicat Premium Data Transfer
Source Server : local
Source Server Type : MySQL
Source Server Version : 50725
Source Host : localhost:3306
Source Schema : elbf_prod
Target Server Type : MySQL
Target Server Version : 50725
File Encoding : 65001
Date: 24/11/2020 18:59:48
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for hx_order
-- ----------------------------
DROP TABLE IF EXISTS `hx_order`;
CREATE TABLE `hx_order` (
`id` varchar(24) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`buyer_id` varchar(24) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家id',
`phone_number` varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`order_amount` decimal(14, 2) NOT NULL COMMENT '订单金额',
`payment_amount` decimal(14, 2) NOT NULL COMMENT '实际支付金额',
`order_status` tinyint(4) NOT NULL DEFAULT 10 COMMENT '订单状态',
`order_time` datetime(0) NOT NULL COMMENT '下单时间',
`cancel_time` datetime(0) NULL DEFAULT NULL COMMENT '订单取消时间',
`close_time` datetime(0) NULL DEFAULT NULL COMMENT '订单关闭时间',
`confirm_receipt_time` datetime(0) NULL DEFAULT NULL COMMENT '物流完成时间,从物流数据中获取',
`coupon_amount` decimal(14, 2) NOT NULL COMMENT '优惠券优惠金额',
`created_time` datetime(0) NOT NULL COMMENT '创建时间',
`platform_id` varchar(24) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '所属平台id',
`service_id` varchar(24) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '服务id',
`wechat_open_id` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '微信id',
`entity_status` tinyint(4) NOT NULL DEFAULT 1 COMMENT '实体状态,1为有效,-1为删除',
`is_evaluated` tinyint(4) NOT NULL DEFAULT 0 COMMENT '买家需要评价订单(0:无,1:是)',
`finish_time` datetime(0) NULL DEFAULT NULL COMMENT '订单完成时间',
`freight` decimal(14, 2) NULL DEFAULT NULL COMMENT '运费',
`freight_model` decimal(14, 2) NULL DEFAULT NULL COMMENT '运费模式',
`is_invoiced` tinyint(4) NOT NULL DEFAULT 0 COMMENT '是否已经开具发票(0:无,0:有)',
`last_modified_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '最近修改时间',
`member_discount_amount` decimal(14, 2) NOT NULL COMMENT '会员折扣金额',
`order_goods_return_status` tinyint(4) NOT NULL DEFAULT 10 COMMENT '订单退货状态',
`pay_succeed_time` datetime(0) NULL DEFAULT NULL COMMENT '订单支付成功时间',
`payment_type` tinyint(4) NULL DEFAULT NULL COMMENT '支付类型',
`promotion_amount` decimal(14, 2) NOT NULL COMMENT '促销优惠金额',
`seller_id` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`share_people_open_id` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分享人的openId',
`area_code` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`contact_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`full_address` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`shop_id` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`total_discount_amount` decimal(14, 2) NOT NULL COMMENT '总优惠金额',
`version` mediumint(8) UNSIGNED NOT NULL DEFAULT 1 COMMENT '乐观锁',
`invoice_id` varchar(24) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`delivery_company` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`delivery_no` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`delivery_remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`delivery_time` datetime(0) NULL DEFAULT NULL,
`shipment_type` int(11) NULL DEFAULT NULL,
`delivery_type` smallint(6) NOT NULL COMMENT '配送类型 1.快递 2。自提',
`address_id` varchar(24) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '地址ID',
`unify_contact_id` bigint(20) NULL DEFAULT NULL COMMENT '核销管理员id',
`is_parent_order` tinyint(4) NOT NULL DEFAULT 0 COMMENT '是否是父订单',
`parent_order_id` varchar(24) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '父订单id',
`goods_code` int(11) NULL DEFAULT NULL COMMENT '提货码',
`platform_order_id` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '平台订单号',
`logistic_information` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '自提物流说明',
`settlement_status` tinyint(4) NULL DEFAULT 1 COMMENT '结算状态,1出账,2待结算,3已结算',
PRIMARY KEY (`id`) USING BTREE,
INDEX `orderStatus`(`buyer_id`, `order_status`) USING BTREE,
INDEX `FK6keg0arntrk2aos8rpflqkfa0`(`invoice_id`) USING BTREE,
CONSTRAINT `FK6keg0arntrk2aos8rpflqkfa0` FOREIGN KEY (`invoice_id`) REFERENCES `hx_order_invoice` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
|
SELECT
c2.concept_id AS conceptId,
c2.concept_name AS conceptName,
ar1.count_value AS countValue
FROM @results_database_schema.achilles_results ar1
INNER JOIN @vocab_database_schema.concept c2 ON CAST(CASE WHEN isNumeric(ar1.stratum_1) = 1 THEN ar1.stratum_1 ELSE null END AS INT) = c2.concept_id
WHERE ar1.analysis_id = 505 |
Update Calendar
Set price = replace(price,'$','');
Update Calendar
Set price = replace(price,',','');
Alter table Calendar
Alter price type numeric Using price::numeric;
Update Calendar
Set adjusted_price = replace(adjusted_price,'$','');
Update Calendar
Set adjusted_price = replace(adjusted_price,',','');
Alter table Calendar
Alter adjusted_price type numeric Using adjusted_price::numeric; |
-- a distinção pode ser feita com o nome da tabela ou com um alias
SELECT A.ID, A.CPF, A.NOME, C.CODIGO, C.DATA_INICIO, C.DATA_FIM, C.VALOR_FINAL
FROM ALUNO A, CONTRATO C
WHERE A.ID = C.ALUNO_ID AND A.ID = 30
ORDER BY A.NOME, C.DATA_INICIO;
-- select entre aluno, contrato, item e curso
SELECT AL.ID, AL.CPF, AL.NOME, CO.CODIGO, CS.NOME
FROM ALUNO AL, CONTRATO CO, ITEM IT, CURSO CS
WHERE
AL.ID = CO.ALUNO_ID AND
CO.ID = IT.CONTRATO_ID AND
CS.ID = IT.CURSO_ID AND
AL.ID = 20
ORDER BY 4, 5;
-- inserindo a expressão (+) na frente das tabela temos todos os registros
-- retornados mesmo em casos que não tem contrato.
SELECT AL.ID, AL.CPF, AL.NOME, CO.CODIGO, CO.VALOR, CS.NOME, CS.VALOR
FROM ALUNO AL, CONTRATO CO, ITEM IT, CURSO CS
WHERE
(
AL.ID = CO.ALUNO_ID(+) AND
CO.ID = IT.CONTRATO_ID(+) AND
IT.CURSO_ID = CS.ID(+)
)
AND AL.ID IN (255, 423) ORDER BY 1, 4, 5;
-- selects onde as colunas não são iguais
SELECT AL.ID, AL.NOME, SUM(CO.VALOR_FINAL) VALOR_TOTAL FROM ALUNO AL, CONTRATO CO
WHERE AL.ID = CO.ALUNO_ID
GROUP BY AL.ID, AL.NOME
ORDER BY 3;
SELECT
AL.ID, AL.NOME,
TO_CHAR(SUM(CO.VALOR_FINAL), 'L99G999D99') VALOR_TOTAL
FROM ALUNO AL, CONTRATO CO
WHERE AL.ID = CO.ALUNO_ID
GROUP BY AL.ID, AL.NOME
ORDER BY 3;
-- mostrar cursos vendidos
SELECT ROWNUM, A.* FROM (
SELECT CS.NOME FROM CURSO CS, ITEM IT
WHERE CS.ID = IT.CURSO_ID
GROUP BY CS.NOME ORDER BY 1
) A;
-- Quantidade de vendas por cursos.
SELECT CS.ID, CS.NOME, COUNT(1) QTDE FROM CURSO CS, ITEM IT
WHERE CS.ID = IT.CURSO_ID
GROUP BY CS.ID, CS.NOME
ORDER BY 3; |
create table T(A int not null);
insert into T values(NULL);
|
# Select Statement
SELECT * FROM Country:
--
SELECT * FROM Country AS 'Life Expectancy' ORDER BY Name:
--
SELECT 'Hello World';
--
SELECT 1 + 2;
--
SELECT Count(*) FROM Country;
# Selecting Rows
SELECT Name, Continent, Region FROM Country;
--
SELECT Name, Continent, Region FROM Country
WHERE Continent='Europe'
LIMIT 5;
# Selecting columns
SELECT * FROM Country ORDER BY Code LIMIT 5;
--
SELECT Name AS Country, Continent AS ISO, Region, Population AS Pop FROM Country ORDER BY Code LIMIT 5;
--
SELECT Name Country, Continent ISO, Region, Population Pop FROM Country ORDER BY Code LIMIT 5;
# Counting Row
SELECT Count(*) FROM Country;
--
SELECT Count(*) FROM Country WHERE Population > 100000000 AND Continent = 'Europe';
# Inserting Data
INSERT INTO Customer (Name, address, city, state, zip) VALUES ('Fred Flinstone','123 Cobblestone Way', 'Bedrock','CA','91234');
SELECT * FROM Customer;
--
INSERT INTO Customer (Name, city, state) VALUES ('Jimi Hendrix','Renton','WA');
SELECT * FROM Customer
# Updating data
UPDATE Customer SET address = '123 Music Avenue', Zip ='98056' WHERE id = 5;
SELECT * FROM Customer;
--
UPDATE Customer SET address = '2603 S Washington Street', Zip ='98056' WHERE id = 5;
SELECT * FROM Customer;
--
UPDATE Customer SET address = '2603 S Washington Street', Zip = Null WHERE id = 5;
SELECT * FROM Customer;
# Deleting Rows in the Table
DELETE * FROM Customer WHERE id=4;
SELECT * FROM Customer;
--
DELETE * FROM Customer WHERE id=5;
SELECT * FROM Customer;
##### Chapter 2
# Creating Tables
CREATE TABLE test (
a INTEGER
b TEXT
);
INSERT INTO test VALUES (1, 'a');
INSERT INTO test VALUES (2, 'b');
INSERT INTO test VALUES (3, 'c');
SELECT * FROM test;
# Deleting a table with DROP TABLE
CREATE TABLE test (a TEXT, b TEXT);
INSERT INTO test VALUES ('one','two');
DROP TABLE test;
SELECT * FRom test; #Select table will fail
--
CREATE TABLE test (a TEXT, b TEXT);
INSERT INTO test VALUES ('one','two');
DROP TABLE test;
DROP TABLE IF EXISTS test;
SELECT * FRom test; #Select table will fail
# Inserting rows into a table
CREATE TABLE test (a INTEGER, b TEXT, c TEXT);
SELECT * FROM test;
INSERT INTO test VALUES (1, 'This', 'Right Here');
SELECT * FROM test;
--
CREATE TABLE test (a INTEGER, b TEXT, c TEXT);
SELECT * FROM test;
INSERT INTO test (b, c)VALUES ('This', 'Right Here');
SELECT * FROM test;
--
CREATE TABLE test (a INTEGER, b TEXT, c TEXT);
SELECT * FROM test;
INSERT INTO test (a, b, c) SELECT id, Name, description FROM item;
SELECT * FROM test;
# Deleting rows from table
DELETE FROM test WHERE a =3;
SELECT * FROM test;
# Understanding Null
SELECT * FROM test WHERE a IS NULL;
--
SELECT * FROM test WHERE a IS NOT NULL
--
DROP TABLE IF EXISTS test;
CREATE TABLE test (
a INTEGER NOT NULL,
b INTEGER NOT Null,
c TEXT)
);
INSERT INTO test (b ,c ) VALUES (1, 'two');
SELECT * FROm test;
--
DROP TABLE test;
# Controlling column behaviours with constraints
CREATE TABLE test( a TEXT, b TEXT, c TEXT );
INSERT INTO test (a, b) VALUES ('one','two');
SELECT * FROM test;
--
CREATE TABLE test( a TEXT, b TEXT, c TEXT DEFAULT 'panda');
INSERT INTO test (a, b) VALUES ('one','two');
SELECT * FROM test;
--
CREATE TABLE test( a TEXT, b TEXT UNIQUE, c TEXT DEFAULT 'panda');
INSERT INTO test (a, b) VALUES ('one','two');
INSERT INTO test (a, b) VALUES ('seven','two');
SELECT * FROM test;
--
CREATE TABLE test( a TEXT, b TEXT UNIQUE, c TEXT DEFAULT 'panda');
INSERT INTO test (a, b) VALUES (NUll, 'two');
INSERT INTO test (a, b) VALUES (NULL,'two');
SELECT * FROM test;
--
CREATE TABLE test( a TEXT, b TEXT UNIQUE NOT NULL, c TEXT DEFAULT 'panda');
INSERT INTO test (a, b) VALUES (NUll, 'two');
INSERT INTO test (a, b) VALUES (NULL,'two');
SELECT * FROM test;
# Changing a schema with ALTER
CREATE TABLE test (a TEXT, b TEXT, c TEXT);
INSERT INTO test VALUES ('one','two','three');
INSERT INTO test VALUES ('two','three','four');
INSERT INTO test VALUES ('three','four','five');
SELECT * FROM test;
ALTER TABLE test ADD d TEXT;
SELECT * FROM test;
--
CREATE TABLE test (a TEXT, b TEXT, c TEXT);
INSERT INTO test VALUES ('one','two','three');
INSERT INTO test VALUES ('two','three','four');
INSERT INTO test VALUES ('three','four','five');
SELECT * FROM test;
ALTER TABLE test ADD d TEXT DEFAULT 'panda';
--
DROP TABLE test;
# CREATING an ID COLUMN
CREATE TABLE test (
id INTEGER PRIMARY KEY,
a INTEGER, b TEXT
);
INSERT INTO test VALUES (10, 'a';
INSERT INTO test VALUES (11, 'b';
# Filtering Data with WHERE, LIKE, and IN
SELECT Name, Continent, Population
FROM Country
WHERE Population < 100000
ORDER BY Population DESC;
--
SELECT Name, Continent, Population
FROM Country
WHERE Population < 100000 OR Population IS NULL
ORDER BY Population DESC;
--
SELECT Name, Continent, Population
FROM Country
WHERE Population < 100000 AND Continent = 'Oceania'
ORDER BY Population DESC;
--
SELECT Name, Continent, Population
FROM Country
WHERE Name LIKE '%island%' # All the records with island in their Name
ORDER BY Name
--
SELECT Name, Continent, Population
FROM Country
WHERE Name LIKE '%island' # All the records with island as the last word in the string
ORDER BY Name
--
SELECT Name, Continent, Population
FROM Country
WHERE Name LIKE '%island' # All the records that start with island
--
SELECT Name, Continent, Population
FROM Country
WHERE Name LIKE '_a%' # Match by, anything as the first character, an 'a' as the Second character, and then the rest of the string
--
SELECT Name, Continent, Population
FROM Country
WHERE Continent IN ('Europe','Asia') # IN Matches valuse in a list or sub selects
ORDER BY Continent
# Selecting Duplicates with SELECT DISTINCT
SELECT Continent from Country;
--
SELECT DISTINCT Continent from Country;
--
CREATE TABLE test(
a INTEGER
b INT);
INSERT INTO test VALUES (1,1);
INSERT INTO test VALUES (2,1);
INSERT INTO test VALUES (3,1);
INSERT INTO test VALUES (4,1);
INSERT INTO test VALUES (5,1);
INSERT INTO test VALUES (1,2);
INSERT INTO test VALUES (1,2);
INSERT INTO test VALUES (1,2);
INSERT INTO test VALUES (1,2);
INSERT INTO test VALUES (1,2);
SELECT DISTINCT a FROM tset;
SELECT * FROM test;
--
SELECT DISTINCT b FROM tset;
SELECT * FROM test;
--
SELECT DISTINCT a,b FROM tset;
SELECT * FROM test;
--
DROP TABLE test;
# Sorting by ORDER BY
SELECT Name from Country;
--
SELECT Name from Country ORDER BY Name;
--
SELECT Name from Country ORDER BY Name DESC;
--
SELECT Name from Country ORDER BY Name ASC;
--
SELECT Name, Continent from Country ORDER BY Continent;
--
SELECT Name, Continent from Country ORDER BY Continent, Name;
--
SELECT Name, Continent, Region from Country ORDER BY Continent DESC, Region, Name;
# Conditional Experssions with CASE
CREATE TABLE booltest (a INTEGER, b INTEGER);
INSERT INTO booltest (1,0);
SELECT * FROM booltest;
--
SELECT * FROM booltest;
SELECT
CASE WHEN a Then 'true' ELSE 'false' END AS boolA,
CASE WHEN b Then 'true' ELSE 'false' END AS boolB,
FROM booltest;
--
SELECT * FROM booltest;
SELECT
CASE a WHEN 1 Then 'true' ELSE 'false' END AS boolA,
CASE b WHEN 1 Then 'true' ELSE 'false' END AS boolB,
FROM booltest;v
--
DROP TABLE test
# Accessting related Table with Join (Missing)
SELECT * FROM left;
SELECT * FROM right;
--
SELECT l.description as left, r.description as right
FROM left as l
JOIN right as r
ON l.id - r.id;
--
SELECT l.description as left, r.description as right
LEFT FROM left as l
JOIN right as r
ON l.id - r.id;
--
DROP TABLE left;
DROP TABLE right;
#Using Related Tables
SELECT * FROM Customers;
SELECT * FROM item;
SELECT * FROM sales;
--
SELECT
c.name AS Cust,
i.name AS Item,
s.price as Price
FROM Customers AS c
INNER JOIN sale AS s
ON s.customer_id = c.id
INNER JOIN item as i
ON s.item_id = i.id
ORDER BY Cust, Item
;
--
INSERT INTO customer (name) VALUES ('Jane Smith')
SELECT
c.name AS Cust,
i.name AS Item,
s.price as Price
FROM Customers AS c
LEFT JOIN sale AS s
ON s.customer_id = c.id
LEFT JOIN item as i
ON s.item_id = i.id
ORDER BY Cust, Item
;
--
SELECT * FROM customer
--
DELETE FROM customer WHERE id = 4
#### Strings
# Finding the length of a string
SELECT LENGTH('string');
--
SELECT Name, LENGTH(Name) AS Len FROM CITY BY Len DESC, Names;
# Selecting a Part of String
SELECT SUBSTR('this string',6);
--
SELECT * FROM album;
--
SELECT
released,
SUBSTR(released, 1, 4, ) AS year,
SUBSTR(released, 6, 2, ) AS month,
SUBSTR(released, 9, 2) AS day,
FROM album
ORDER BY released;
# Trim Function
SELECT ' string ';
--
SELECT TRIM(' string ');
--
SELECT LTRIM(' string ');
--
SELECT RTRIM(' string ');
--
SELECT TRIM('...string ...', '.');
# Upper and Lower Case
SELECT 'StRiNG' = 'string'; #This will be false
--
SELECT Lower('StRiNG') = 'string'; #True
--
SELECT Lower('StRiNG') = Lower('string'); #True
--
SELECT Upper('StRiNG') = Upper'string'); #True
--
SELECT Upper(Name) FROM City ORDER BY Name;
--
SELECT Lower(Name) FROM City ORDER BY Name;
# Finding Type of Value
SELECT (1 + 1.0);
--
SELECT TYPEOF(1 + 1.0);
--
SELECT TYPEOF(1);
--
SELECT TYPEOF('string');
--
SELECT TYPEOF('string' + 'pandas'); #This is an integar
--
SELECT 1 / 2;
--
SELECT 1.0 / 2;
--
SELECT CAST(1 AS REAL) / 2;
--
SELECT 17/5;
--
SELECT 17/5, 17 % 5;
# Round Function
SELECT ROUND (2.55555);
--
SELECT ROUND (2.55555, 3);
--
SELECT ROUND (2.55555, 6);
# Date and Time Functions
-- All Time are in UTC
SELECT DATETIME('now');
s--
SELECT DATE('now');
--
SELECT TIME('now');
--
SELECT DATETIME('now', '+1 day');
--
SELECT DATETIME('now', '+3 days');
--
SELECT DATETIME('now', '-1 month');
--
SELECT DATETIME('now', '+3 hours','+27 minutes', '-1 day', '+3 years');
#### Aggerate Datay
# Aggerate Data
SELECT COUNT(*) FROM Country;
--
SELECT Region, Count(*) FROM Country
GROUP BY Region;
--
SELECT Region, Count(*) AS COUNT FROM Country
GROUP BY Region
ORDER BY Count DESC, Region;
--
SELECT
a.title AS Album,
COUNT(t.track_number) as Tracks
FROM trakcs as t
INNER JOIN album as a
ON a.id = t.ablum_id
GROUP BY a.id
ORDER BY Tracks DESC, Album
--
SELECT
a.title AS Album,
COUNT(t.track_number) as Tracks
FROM trakcs as t
INNER JOIN album as a
ON a.id = t.ablum_id
GROUP BY a.id
HAVING Tracks >= 10
ORDER BY Tracks DESC, Album
--
SELECT
a.title AS Album,
COUNT(t.track_number) as Tracks
FROM trakcs as t
INNER JOIN album as a
ON a.id = t.ablum_id
WHERE a.artist = 'The Beatles'
GROUP BY a.id
HAVING Tracks >= 10
ORDER BY Tracks DESC, Album
--
SELECT COUNT(*) FROM Country;
--
SELECT COUNT(Population) FROM Country; #!! Counts only Not null values
--
SELECT AVG(Population) FROM Country;
--
SELECT AVG(Population) FROM Country GROUP BY Region;
--
SELECT MIN(Population), MAX(Population) FROM Country GROUP BY Region;
--
SELECT SUM(Population) FROM Country GROUP BY Region;
# Distinct Aggregation
SELECT COUNT(HeadofState) FROM Country ORDER BY HeadofState;
--
SELECT COUNT(DISTINCT(HeadofState)) FROM Country ORDER BY HeadofState;
#### Transactions
# Using Transactions
BEGIN TRANSACTION;
INSERT INTO widegtSales(inv_id, quan, price) VALUES (1, 5, 500);
UPDATE widegtInventory SET onhand = (onhand - 5) WHERE id = 1;
END TRANSACTION
SELECT * FROM widegtInventory;
SELECT * FROM widegtSales
--
BEGIN TRANSACTION;
INSERT INTO widegtInventory( description, onhand) VALUES ('toy', 25);
ROLLBACK;
SELECT * FROM widegtInventory;
SELECT * FROM widegtSales
--
DROP TABLE widegtInventory;
DROP TABLE widegtSales
-- Using Transaction clauses for a shit ton of inserts are way faster
#### Triggers
# Understanding a table of triggers
CREATE TRIGGER newWigetsSale AFTER INSERT ON widegtSales
BEGIN
UPDATE widegtCustomer SET last_order_id = NEW.id WHERE widegtCustomer.id = NEW.customer_id;
END;
# Preventing automatic updates with a trigger
CREATE TRIGGER updateWigetSale BEFORE UPDATE ON widegtSales;
BEGIN
SELECT RAISE(ROLLBACK, 'cannot update table "widegtSale"' FROM widegtSale
WHERE id = NEW.id AND reconciled = 1;
END
;
--
BEGIN TRANSACTION;
UPDATE widegtSale SET quan = 9 WHERE id = 2;
END TRANSACTION;
SELECT * FROM widegtSale;
# Creating Timestamps via Trigger
CREATE TRIGGER stampSale AFTER INSERT on widegtSale;
BEGIN
UPDATE widegtSale SET stamp = DATETIME('now') WHERE id=NEW.id;
UPDATE widegtCustomer SET last_order_id = NEW.id, stamp = DATETIME('now')
WHERE widegtCustomer.id = NEW.customer_id;
INSERT INTO widegtLog (stamp, event, username, tablename, table_id)
VALUES (DATETIME('now'), 'INSERT','TRIGGER','widegtSale',NEW.id);
END
#### Subselects and Views
# A simple subselect
SELECT
SUBSTR(a, 1, 2) AS State,
SUBSTR(a, 3) AS SCode,
SUBSTR(b, 1, 2) AS Country,
SUBSTR(b, 3) AS CCode
FROM t
--
SELECT co.Name, ss.CCode FROM(
(SELECT
SUBSTR(a, 1, 2) AS State,
SUBSTR(a, 3) AS SCode,
SUBSTR(b, 1, 2) AS Country,
SUBSTR(b, 3) AS CCode
FROM t) AS ss
INNER JOIN Country AS co ON co.Code2 = ss.Country
--
DROP TABLE t;
# Searching within a result set
SELECT album_id FROM track WHERE duration <= 90;
SELECT DISTINCT album_id FROM track WHERE duration <= 90
);
--
SELECT a.title AS album, a.artist, t.track_number AS Seq, t.title, t.duration AS secs
FROM album AS a
INNER JOIN as t
ON t.album_id = a.id
WHERE a.id IN (SELECT DISTINCT ablum_id FROM track WHERE duration <= 90)
ORDER BY a.title, t.track_number
;
# Creating a view
SELECT id, ablum_id, title, track_number, duration / 60 AS m
--
CREATE VIEW trackView
SELECT id, ablum_id, title, track_number, duration / 60 AS m
--
SELECT a.title AS album, artist, t.track_number AS seq, t.title, t.m, t.s
FROM album as a
INNER JOIN trackView as t
ON t.album_id = a.id
ORDER BY a.title, t.track_number
;
--
DROP VIEW trackView;
# Creating a joined view
SELECT a.artist AS artist,
a.title as album,
t.title as track,
t.track_number as trackno,
t.duration / 60 AS m,
t.duration % 60 AS s
FROM track as t
INNER JOIN album as a
ON a.id = t.album_id
;
SELECT * FROM joinedAlbum WHERE artist = 'Jimi Hendrix';
--
SELECT artist, album, track, trackno,
m|| ':' || CASE WHEN s < 10 THEN "0" || s ELSE s END AS duration
FROM joinedAlbum;
--
DROP VIEW joinedAlbum;
#### CRUD Applications
-- create, read, update, delete
|
USE StudyTree;
DROP PROCEDURE IF EXISTS create_study_group;
DELIMITER //
CREATE PROCEDURE create_study_group
(IN startTime datetime, IN endTime datetime, IN classId int, IN uid int)
BEGIN
INSERT INTO study_groups (class_id, start_time, end_time)
VALUES (classId, startTime, endTime);
call join_study_group(uid, last_insert_id());
END //
DELIMITER ;
|
#事物(transaction)
#为了完成某个业务而执行的一条或者多条sql语句,sql语句的最小逻辑工作单元,保证数据的完整性
#事物特性
#原子性:事物是一个完整的操作,事物的各项操作都不不能分开的
#持久性:事物完成后,它对数据库的修改将永久保存
#隔离性:并发事务之间彼此隔离,独立,他不应该以任何方式依赖于或影响
#一致性:事物完成时,数据必须处于一致状态
/*
A数据库服务端(支付一方),B数据库服务端(接受一方)钱没收到,也就是数据没有提交到数据库中,这是必须需要事物来处理该问题
*/
CREATE TABLE bank(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(10),money DOUBLE );
INSERT INTO bank VALUES(NULL,"王云龙",1000),(NULL,"李浩哲",500);
#1.查询自动提交的状态1或者ON 则为自动提交 0或OFF则为手动提交
SHOW VARIABLES LIKE "autocommit";
#2.设置提交状态
SET autocommit = 0; #设置提交状态为手动
UPDATE bank SET money = money - 200 WHERE NAME = "王云龙";
UPDATE bank SET money = money + 200 WHERE NAME = "李浩哲";
#以上两条sql语句是在事物中执行的
SET autocommit = 1; #设置提交状态为自动
#回滚 rollback
INSERT INTO bank VALUES(NULL,"高轲",500),(NULL,"丁静君",500),(NULL,"张欣如",500),(NULL,"闫薇",500),(NULL,"坤哥",500);
COMMIT;
INSERT INTO bank VALUES(NULL,"高阶元素",1000);
DELETE
ROLLBACK;
#约束:约束就是给表字段添加的限制条件
#添加非空约束字段的值不能为null
CREATE TABLE mytable (id INT PRIMARY KEY AUTO_INCREMENT,ename VARCHAR(10) NOT NULL);
INSERT INTO mytable VALUES (NULL,NULL);
#unique 唯一
CREATE TABLE mytable1 (id INT PRIMARY KEY AUTO_INCREMENT,ename VARCHAR(10) UNIQUE NOT NULL);
INSERT INTO mytable1 VALUES (NULL,"测试1");
#主键约束:primary key添加了主键约束的字段,值不能为null,也不能重复
#一个表只能有一个主键
CREATE TABLE mytable2(id INT PRIMARY KEY);
INSERT INTO mytable2 VALUES(1);
#删除主键索引
SHOW CREATE TABLE mytable2;
ALTER TABLE mytable2 DROP PRIMARY KEY;
#外键约束是保证一个或两个表之间的参照完整性保持数据一致性
#表的外键可以另一张表的主键,这张表也可以是唯一约束
#外键有重复,可以为空
#references
#创建外键约束方式一
#年级表
CREATE TABLE classes(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(10));
#学生表
CREATE TABLE student(id INT PRIMARY KEY AUTO_INCREMENT ,NAME VARCHAR(10),class_id INT REFERENCES classes(id));
#创建外键约束方式二
CREATE TABLE student2(id INT PRIMARY KEY AUTO_INCREMENT ,NAME VARCHAR(10),classes_id INT CONSTRAINT pk_stu_id )
#索引:用来加快查询的技术很多,其中最重要的就是索引(index)
#1.通常索引能够快速提高查询速度
#2.如果不使用索引,MySQL必须从第一条记录开始然后读整个表直到找出相关的行,表越大,花费的时间越长
#索引可以用来改善性能,有时索引可能降低性能(如果表的数据很少就不需要添加索引,否则会降低性能)
#1.创建索引语法:create index 索引名字 on 表名(字段名)
#2.删掉索引语法:drop index 索引名 on 表名
#3.查看索引:show index from 表名
#在MySQL中选择数据库并且导入sql文件:例如:e盘下的sql文件item_backup.sql
#source e:/item_backup.sql;//此处不能执行,必须在黑框里面执行
#快速导入文件的方法:use store_ykt;
#source 盘:/文件名.sql;//文件夹不要出现中文,此处为直接在盘里面存储的
SELECT COUNT(*) FROM item2;
SHOW INDEX feom emp;
SELECT * FROM item2 WHERE title="100";-- 非索引查询速度相比较慢,如果数据库大的话会严重影响速度
SELECT * FROM item2 WHERE id=21456;-- 索引查询速度很快
# 创建索引
CREATE INDEX index_num ON item2(num);
SELECT * FROM item2 WHERE num=857;
CREATE UNIQUE INDEX index_my2 ON mytable2(ename)
CREATE TABLE mytable2(id INT PRIMARY KEY AUTO_INCREMENT ,ename VARCHAR(10));
INSERT INTO mytable2 VALUES(NULL,"");
#按照下面标准选择建立索引列
#1.频繁搜索的列
#2.经常用作查询选择的列
#3.经常排序,分组的列
#4.经常用作连接的列(主键/外键)
#请不要使用下面的列创建索引
#1.仅包含几个不同值的列
#2.表中仅包含几行数据
/*主键,外键,索引的区别
主键 外键 索引
唯一标识一条记录,不能有 表的外键是另一张表的主键, 该字段没有重复值,但可以有一个空值
定义: 重复的,不允许为空 外键可以有重复的,可以有空值 (也可有重复值)
作用: 主键是用来保证数据完整性 是用来和其他建立联系用的 是提高查询,排序的速度
个数: 主键只能有一个 一个表可以有多个外键 一个表可以有多个索引
*/
#系统变量
#说明:变量由系统提供,不是用户定义,属于服务器层面
#使用语法
#1查看所有系统变量
SHOW GLOBAL/SESSION VARIABLES LIKE "%%";
#2查看全局变量
SHOW GLOBAL VARIABLES;
#查看会话变量session 可以省略
SHOW SESSION VARIABLES;
#查看全部分局变量带有"char"
SHOW GLOBAL VARIABLES LIKE "%char%";
#查看会话带有"char"
SHOW VARIABLES LIKE "%char%";
#3.查看指定的某个系统的变量
SELECT @@GLOBAL
#查看系统变量autocommit的值
SELECT @@global.autocommit;
#查看全局变量autocommit的值
#4.为某个系统变量赋值
#set @@global/session 系统变量的名 = 值;
#给全局变量autocommit赋值
SET @@global.autocommit = 0;
#给会话变量antocommit赋值
SET @@autocommit = 0;
/*自定义变量
@说明 变量是用户自定义的并不是由系统提供的
使用步骤
声明
赋值
使用(查看,比较,运算)
1.用户变量:
作用域:针对当前会话有效,等同于会话变量的作用域一样,只对当前有效
2.局部变量:
作用域:仅仅在定义它的begin in end中有效,必须应用在begin end 中的第一句话
*/
#声明并初始化用户变量
方式1 SET @用户变量名 = 值
SET @aname = "坤哥";
#查看用户变量名
SELECT @ename;
方式2 SET @用户变量名 := 值;
SET @pname := "呵呵";
SELECT @pname;
#赋值:通过set或者select
#方式1: set @用户变量名 = 值
#方式2: set @用户变量名 =: 值
#方式3: select @用户变量名 =: 值
#方式4: 通过select into
SELECT COUNT(*) INTO @c FROM emp;
SELECT @c;
/*
局部变量:
1.声明
declare 变量名 类型 default 值
2.赋值
set 局部变量 = 值;
3.查看
select 局部变量;
*/
DECLARE yname VARCHAR(10) DEFAULT 9;
DELIMITER $;
CREATE PROCEDURE my9();
BEGIN
#设置全局变量
DECLARE result VARCHAR(10) DEFAULT "";
SET result = "测试";
SELECT result;
END $
#案例
CREATE PROCEDURE my10(IN ename VARCHAR(10),IN pwd VARCHAR(10))
BEGIN
#声明局部变量
DECLARE result VARCHAR(10) DEFAULT "";
SELECT COUNT(*) INTO result FROM admin WHERE user_name = ename AND user_password = pwd;
SELECT IF(result > 0,"成功","失败");
END $
CALL my10("高阶","123456") $
#创建带inout模式参数的存储过程
#传入创建存储过程实现传入a和b两个值最终a和b都翻倍并返回
CREATE PROCEDURE my11(INOUT a INT,INOUT b INT)
BEGIN
SET a = a * 2;
SET b = b * 2;
END $
#设置变量
SET @x1 = 10;
SET @x2 = 20;
CALL my11(@x1,@x2) $
SELECT @x1,@x2 $
#创建存储过程实现根据员工编号查询员工的领导编号
CREATE PROCEDURE my12(INOUT n INT)
BEGIN
SELECT mgr INTO n FROM emp WHERE empno = n;
END $
SET @mgr = 7369 $ |
47.
SELECT nom, prenom, emploi, service from employes inner join services on employes.noserv = services.noserv;
48.
SELECT nom, emploi, emp.noserv, service from emp inner join serv on emp.noserv = serv.noserv;
49.
SELECT nom, emploi, emp.noserv, service from emp as E inner join serv as S on E.noserv = S.noserv;
50.
SELECT nom, emploi, S.* from emp as E inner join serv as S on E.noserv = S.noserv;
51.
SELECT E1.nom, E1.embauche, E2.nom, E2.embauche
FROM emp as E1 inner join emp as E2 ON E1.sup = E2.noemp
WHERE E1.embauche < E2.embauche;
ORDER BY E1.nom, E2.nom;
52.
SELECT prenom, emploi from emp where emploi = "DIRECTEUR"
UNION
SELECT prenom, emploi from emp where emploi = "TECHNICIEN" and noserv = 1;
53.
SELECT noserv, service, ville from serv
WHERE noserv not in (SELECT distinct noserv FROM emp);
54.
SELECT DISTINCT emp.noserv, service, ville from emp inner join serv on emp.noserv = serv.noserv;
55.
SELECT E.*, S.ville FROM emp AS E INNER JOIN serv AS S ON E.noserv = S.noserv
WHERE S.ville = "LILLE";
ou
SELECT * FROM emp WHERE noserv IN (SELECT noserv FROM serv WHERE ville = "LILLE");
56.
SELECT * FROM emp
WHERE sup in (SELECT sup FROM emp WHERE nom = "DUBOIS")
AND nom != "DUBOIS";
57.
SELECT * FROM emp WHERE embauche = (SELECT embauche FROM emp WHERE nom = "DUMONT");
58.
SELECT nom, embauche FROM emp
WHERE embauche < (SELECT embauche FROM emp WHERE nom = "MINET")
ORDER BY embauche;
59.
SELECT nom, prenom, embauche FROM emp
WHERE embauche < (SELECT MIN(embauche) FROM emp WHERE noserv = 6);
60.
SELECT nom, prenom, (sal + ifnull(comm, 0)) as revenu_mensuel FROM emp
WHERE (sal + ifnull(comm, 0)) > (SELECT MIN(sal + ifnull(comm, 0))
FROM emp
WHERE noserv = 3
)
ORDER BY 3;
61.
SELECT nom, noserv, emploi, sal
FROM emp AS E INNER JOIN serv AS S ON E.noserv = S.noserv
WHERE S.ville = (SELECT ville
FROM emp AS E INNER JOIN serv AS S ON E.noserv = S.noserv
WHERE nom = "HAVET");
62.
SELECT * FROM emp
WHERE noserv = 1
AND emploi IN (SELECT DISTINCT emploi FROM emp WHERE noserv = 3);
63.
SELECT * FROM emp
WHERE noserv = 1
AND emploi NOT IN (SELECT DISTINCT emploi FROM emp WHERE noserv = 3);
64.
SELECT nom, prenom, emploi, sal FROM emp
WHERE emploi =(SELECT emploi FROM emp WHERE nom = "CARON")
AND sal > (SELECT sal FROM emp WHERE nom = "CARON");
65.
SELECT * FROM emp
WHERE noserv = 1
AND emploi in(SELECT distinct emploi
FROM emp inner join serv
on emp.noserv = serv.noserv
WHERE serv.service = "VENTES");
66.
SELECT nom, prenom, emploi, serv.ville
FROM emp INNER JOIN serv ON emp.noserv = serv.noserv
WHERE serv.ville = "LILLE"
AND emploi = (SELECT emploi
FROM emp
WHERE nom = "RICHARD")
ORDER BY nom;
67.
SELECT prenom, nom, sal, noserv FROM emp as E1
WHERE sal > (SELECT AVG(sal) FROM emp as E2 WHERE E1.noserv = E2.noserv)
ORDER BY noserv;
68.
SELECT nom, prenom, emp.noserv, embauche
FROM emp inner join serv on emp.noserv = serv.noserv
WHERE service = "INFORMATIQUE"
AND date_format(embauche, "%Y") IN(
SELECT distinct date_format(embauche, "%Y") as ANNEE
FROM emp inner join serv on emp.noserv = serv.noserv
WHERE service = "VENTES");
69.
SELECT nom, prenom, emploi, ville
FROM emp AS E1 inner join serv on emp.noserv = serv.noserv
WHERE noserv <> (SELECT noserv FROM emp As E2 WHERE E2.noemp = E1.sup);
70.
SELECT noemp, nom, prenom, service, (sal + ifnull(comm, 0)) as REVENU
FROM emp inner join serv on emp.noserv = serv.noserv
WHERE noemp IN (SELECT distinct sup FROM emp)
ORDER BY 5 DESC;
71.
SELECT nom, emploi , round((sal + ifnull(comm, 0)), 2) as revenu
FROM emp;
72.
SELECT * from emp WHERE ifnull(comm, 0) > sal * 2;
73.
SELECT nom, prenom, emploi, round((ifnull(comm, 0)/(ifnull(comm, 0) +sal)) * 100, 2) as "%commission"
FROM emp
WHERE emploi = "VENDEUR"
ORDER BY "%commission";
74.
SELECT nom, prenom, service, round(sal + ifnull(comm, 0)) * 12 as "revenu_annuel"
FROM emp inner join serv on emp.noserv = serv.noserv
WHERE emploi = "VENDEUR";
78.
SELECT nom, emploi,
sal / 22 AS salaire_jounalier_SA,
round(sal / 22, 2) AS salaire_jounalier_ARRONDI,
sal / 22 / 8 AS salaire_horaire_SA,
round(sal / 22 / 8, 2) AS salaire_horaire_ARRONDI
FROM emp
WHERE noserv in (3, 5, 6);
79.
SELECT nom, emploi,
sal / 22 AS salaire_jounalier_SA,
truncate(sal / 22, 2) AS salaire_jounalier_ARRONDI,
sal / 22 / 8 AS salaire_horaire_SA,
truncate(sal / 22 / 8, 2) AS salaire_horaire_ARRONDI
FROM emp
WHERE noserv in (3, 5, 6);
80.
SELECT service , ville,
concat(rpad(service, (select max(length(service)) from serv), "-"), "--->", ville) AS "service ---> ville"
FROM serv;
81.
SELECT nom, emploi, (
case emploi
when 'PRESIDENT' then 1
when 'DIRECTEUR' then 2
when 'COMPTABLE' then 3
when 'VENDEUR' then 4
when 'TECHNICIEN' then 5
else 0
end
) AS "CODE_EMPLOI"
FROM emp
ORDER BY 3;
82.
SELECT noserv, prenom, emploi, (
case noserv
when 1 then "*****"
else nom
end
) as toto
FROM emp;
83.
SELECT substr(service, 1, 5)
FROM serv;
84.
select * from emp where date_format(embauche, "%Y") = "1988";
85.
select
upper(nom) as "MAJ",
concat(upper(left(nom, 1)), lower(right(nom, length(nom) - 1))) AS "CAP",
lower(nom) AS "MIN"
from emp;
85.bis
select
upper(nom) AS "MAJ",
concat(upper(substr(nom, 1, 1)), lower(substr(nom, 2, length(nom)))) AS "CAP"
lower(nom) AS "MIN"
From emp;
86.
select nom, locate("M", nom) as "POS de M", locate("E", nom) as "POS de E"
from emp;
87.
select service, length(service) AS "LENGTH" from serv;
88.
SELECT sal, rpad('', sal/2000, '#')
FROM emp;
89.
SELECT nom, emploi, embauche
FROM emp
WHERE noserv = 6;
90.
SELECT nom, emploi, embauche, date_format(embauche, "%d-%m-%y")
FROM emp
WHERE noserv = 6;
91.
SELECT nom, emploi, embauche, date_format(embauche, "%W %d %M %Y")
FROM emp
WHERE noserv = 6;
92.
SELECT nom, emploi, embauche, date_format(embauche, "%W %d %b %y")
FROM emp
WHERE noserv = 6;
93.
SELECT nom, emploi, embauche, date_format(embauche, "%y %b %d")
FROM emp
WHERE noserv = 6;
94.
SELECT nom, emploi, embauche, date_format(embauche, "%W-%d-%M-%Y")
FROM emp
WHERE noserv = 6;
95.
SELECT nom, emploi, embauche, datediff(sysdate(), embauche)
FROM emp;
96.
SELECT nom, emploi, embauche, timestampdiff(month, embauche, sysdate())
FROM emp;
97.
SELECT nom, emploi, embauche,
concat(date_format(embauche, "%d-%m-"), date_format(embauche, "%Y") + 12) AS "dd-mm-yyyy",
concat(date_format(embauche, "%Y") + 12, date_format(embauche, "-%m-%d")) AS "yyyy-mm-dd"
FROM emp;
98.
SELECT nom, emploi, embauche
FROM emp
WHERE timestampdiff(year, embauche, sysdate()) > 25;
99.
select timestampdiff(month, "1990-01-01", sysdate());
100.
select timestampdiff(day, "1990-01-01", sysdate());
101.
SELECT avg((sal + ifnull(comm, 0)))
FROM emp
WHERE emploi = "VENDEUR";
102.
SELECT emploi, floor(avg((sal + ifnull(comm, 0)))) as revenu_moyen
FROM emp
group by emploi;
103.
SELECT SUM(sal) as somme_sal, SUM(comm) AS somme_comm
FROM emp
WHERE emploi = "VENDEUR";
104.
SELECT max(sal), min(sal), max(sal)-min(sal)
FROM emp
105.
SELECT count(noemp), date_format(embauche, "%Y") as annee
FROM emp
GROUP BY annee;
106.
SELECT service, length(service) FROM serv
where length(service) = (SELECT min(length(service)) FROM serv);
107.
SELECT * FROM emp
WHERE sal + ifnull(comm, 0) =(SELECT max(sal + ifnull(comm, 0)) FROM emp);
108.
SELECT count(*) FROM emp WHERE noserv = 3 AND ifnull(comm, 0) != 0;
109.
SELECT count(distinct emploi)
FROM emp
WHERE noserv = 1;
110.
SELECT count(*)
FROM emp
WHERE noserv = 3;
111.
Select noserv, round(avg(sal),0)
From emp
group by noserv;
112.
Select noserv, emploi, avg(sal) * 12
From emp
where emploi not in ("DIRECTEUR", "PRESIDENT")
group by noserv;
113.
select noserv, emploi, count(*) AS effectif, avg(sal)
from emp
group by noserv, emploi;
114.
select service, emploi, count(*) AS effectif, avg(sal)
from emp inner join serv on emp.noserv = serv.noserv
group by service, emploi;
115.
select emploi, count(*), avg(sal)
from emp
group by emploi
having count(*) >= 2;
116.
select serv.*
from emp inner join serv on emp.noserv = serv.noserv
where emploi = "VENDEUR"
group by noserv
having count(*) >= 2;
117.
select serv.*, avg(ifnull(comm, 0)) as comm_average, avg(sal) / 4 as sal_average
from emp inner join serv on emp.noserv = serv.noserv
group by emp.noserv
having avg(ifnull(comm, 0)) > avg(sal) / 4;
118.
SELECT emploi, avg(sal)
From emp
GROUP BY emploi
HAVING avg(sal) > (SELECT avg(sal) From emp WHERE emploi = "DIRECTEUR");
119.
SELECT noserv, count(comm) as "HAS_COMM", count(*) - count(comm) AS "HAS_NO_COMM"
FROM emp
GROUP BY noserv;
120.
SELECT emploi, count(*), AVG(sal) AS "AVG SAL", SUM(sal) AS "TOTAL SAL",
AVG(ifnull(comm, 0)) AS "AVG COMM", SUM(ifnull(comm, 0)) AS "TOTAL COMM"
FROM emp
GROUP BY emploi;
/*Pour ces exercices, vous devez vous connecter sous votre identifiant et faire une copie
des tables EMP et SERV.*/
SET AUTOCOMMIT = 0;
create table emp2
(
noemp int(4) not null,
nom varchar(20),
prenom varchar(20),
emploi varchar(20),
sup int(4),
embauche date,
sal float(9,2),
comm float(9,2),
noserv int(2)
);
alter table emp2
add constraint PK_EMP2 primary key (noemp);
create table serv2
(
noserv int(2) not null,
service varchar(20),
ville varchar(20)
);
alter table serv2
add constraint PK_SERV2 primary key(noserv);
insert into emp2 values (1000,'LEROY','PAUL','PRESIDENT',null,'1987-10-25',55005.5,null,1);
insert into emp2 values (1100,'DELPIERRE','DOROTHEE','SECRETAIRE',1000,'1987-10-25',12351.24,null,1);
insert into emp2 values (1101,'DUMONT','LOUIS','VENDEUR',1300,'1987-10-25',9047.9,0,1);
insert into emp2 values (1102,'MINET','MARC','VENDEUR',1300,'1987-10-25',8085.81,17230,1);
insert into emp2 values (1104,'NYS','ETIENNE','TECHNICIEN',1200,'1987-10-25',12342.23,null,1);
insert into emp2 values (1105,'DENIMAL','JEROME','COMPTABLE',1600,'1987-10-25',15746.57,null,1);
insert into emp2 values (1200,'LEMAIRE','GUY','DIRECTEUR',1000,'1987-03-11',36303.63,null,2);
insert into emp2 values (1201,'MARTIN','JEAN','TECHNICIEN',1200,'1987-06-25',11235.12,null,2);
insert into emp2 values (1202,'DUPONT','JACQUES','TECHNICIEN',1200,'1988-10-30',10313.03,null,2);
insert into emp2 values (1300,'LENOIR','GERARD','DIRECTEUR',1000,'1987-04-02',31353.14,13071,3);
insert into emp2 values (1301,'GERARD','ROBERT','VENDEUR',1300,'1999-04-16',7694.77,12430,3);
insert into emp2 values (1303,'MASURE','EMILE','TECHNICIEN',1200,'1988-06-17',10451.05,null,3);
insert into emp2 values (1500,'DUPONT','JEAN','DIRECTEUR',1000,'1987-10-23',28434.84,null,5);
insert into emp2 values (1501,'DUPIRE','PIERRE','ANALYSTE',1500,'1984-10-24',23102.31,null,5);
insert into emp2 values (1502,'DURAND','BERNARD','PROGRAMMEUR',1500,'1987-07-30',13201.32,null,5);
insert into emp2 values (1503,'DELNATTE','LUC','PUPITREUR',1500,'1999-01-15',8801.01,null,5);
insert into emp2 values (1600,'LAVARE','PAUL','DIRECTEUR',1000,'1991-12-13',31238.12,null,6);
insert into emp2 values (1601,'CARON','ALAIN','COMPTABLE',1600,'1985-09-16',33003.3,null,6);
insert into emp2 values (1602,'DUBOIS','JULES','VENDEUR',1300,'1990-12-20',9520.95,35535,6);
insert into emp2 values (1603,'MOREL','ROBERT','COMPTABLE',1600,'1985-07-18',33003.3,null,6);
insert into emp2 values (1604,'HAVET','ALAIN','VENDEUR',1300,'1991-01-01',9388.94,33415,6);
insert into emp2 values (1605,'RICHARD','JULES','COMPTABLE',1600,'1985-10-22',33503.35,null,5);
insert into emp2 values (1615,'DUPREZ','JEAN','BALAYEUR',1000,'1998-10-22',6000.6,null,5);
commit;
insert into serv2 values (1,'DIRECTION','PARIS');
insert into serv2 values (2,'LOGISTIQUE','SECLIN');
insert into serv2 values (3,'VENTES','ROUBAIX');
insert into serv2 values (4,'FORMATION','VILLENEUVE D''ASCQ');
insert into serv2 values (5,'INFORMATIQUE','LILLE');
insert into serv2 values (6,'COMPTABILITE','LILLE');
insert into serv2 values (7,'TECHNIQUE','ROUBAIX');
commit;
/*121 : Augmenter de 10% ceux qui ont un salaire inférieur au salaire moyen. Valider.*/
Set autocommit = 0;
UPDATE emp2
SET sal = 1.1*(sal)
where sal<(select avg(sal)
from emp);
Commit;
/*122 : Insérez vous comme nouvel employé embauché aujourd’hui au salaire que vous
désirez. Valider.*/
Set autocommit = 0;
select @nextId := max(noemp)+1 from emp2;
insert into emp2 (noemp, nom, prenom, sal, embauche, emploi, noserv, sup)
values ( @nextId,'SACI','MOHAMED-ELHADI',3000,sysdate(),'DEVELOPPEUR', 5, 1200);
select @nextId := max(noemp)+1 from emp2;
select @moy := avg(sal) from emp2;
insert into emp2 (noemp, nom, prenom, sal, embauche, emploi, noserv, sup)
values (@nextId, 'DELSART', 'THIBAULT', @moy, sysdate(), 'PUPITREUR', 5, 1500);
commit
/*123 : Effacer les employés ayant le métier de SECRETAIRE. Valider.*/
Set autocommit = 0;
DELETE FROM emp2
WHERE emploi='SECRETAIRE';
commit;
/*124 : Insérer le salarié dont le nom est MOYEN, prénom Toto, no 1010, embauché le
12/12/99, supérieur 1000, pas de comm, service no 1, salaire vaut le salaire moyen des
employés. Valider.*/
Set autocommit = 0;
select @salMoy := AVG(sal) from emp2;
insert into emp2 (noemp, nom, prenom, sal, embauche, emploi, sup, noserv)
values ( 1010,'MOYEN','Toto',@salMoy,'1999-12-12','DEVELOPPEUR',1000,1);
commit;
/*125 : Supprimer tous les employés ayant un A dans leur nom. Faire un SELECT sur
votre table pour vérifier cela. Annuler les modifications et vérifier que cette action
s’est bien déroulée.*/
SET AUTOCOMMIT = 0;
delete from emp2
where nom like '%A%';
select *
from emp2;
rollback;
select *
from emp2;
/*126 :
Créer une table PROJET avec les colonnes suivantes:
numéro de projet (noproj), type numérique 3 chiffres, doit contenir une valeur. nom de projet (nomproj), type caractère, longueur = 10
budget du projet (budget), type numérique, 6 chiffres significatifs et 2 décimales.
Vérifier l'existence de la table PROJET.
Faire afficher la description de la table PROJET.
C’était une erreur!!! Renommez la table PROJET en PROJ
.*/
create table projet
(
noproj int(3) primary key,
nomproj varchar(10),
budget float(8,2)
);
/* vérifier si la table existe */
/* ou */
use emploi;
show tables;
/* ou */
select *
from proj;
DESCRIBE projet;
rename table projet to proj;
/*127 :
Insérer trois lignes de données dans la table PROJ:
numéros des projets = 101, 102, 103
noms des projets = alpha, beta, gamma
budgets = 250000, 175000, 950000
Afficher le contenu de la table PROJ.
Valider les insertions faites dans la table PROJ.*/
insert into proj (nomproj,noproj,budget) values ('ALPHA', 101,250000);
insert into proj (nomproj,noproj,budget) values ('BETA', 102,175000);
insert into proj (nomproj,noproj,budget) values ('GAMMA', 103,950000);
commit;
select * from proj;
/*128 :
Modifier la table PROJ en donnant un budget de 1.500.000 Euros au projet 103.
Modifier la colonne budget afin d'accepter des projets jusque 10.000.000.000 d’Euros
Retenter la modification demandée 2 lignes au dessus.*/
update proj
set budget=1500000
where noproj=103;
alter table proj
modify budget float(13,2);
update proj
set budget=1500000
where noproj=103;
commit;
select *
from proj;
/*129 :
Ajouter une colonne NOPROJ (type numérique) à la table EMP.
Afficher le contenu de la table EMP.*/
alter table emp2
add noproj int(3);
select *
from emp2;
/* 130 : Affecter les employés dont le numéro est supérieur à 1350 au projet 102, sauf
ceux qui sont déjà affectés à un projet.*/
update emp2
set noproj=102
where noemp>1350
and noproj is null;
commit;
/*131 : Affecter les employés n'ayant pas de projet au projet 103.*/
update emp2
set noproj=103
where noproj is null;
commit;
/*132 : Sélectionner les noms d'employés avec le nom de leur projet et le nom de leur
service.*/
select e.nom,e.prenom,e.emploi, p.nomproj, s.service
from emp2 as e inner join serv2 as s inner join proj as p
on e.noserv=s.noserv and e.noproj = p.noproj;
|
Services for each Customer
Write a query to display a list of all customer names together with a comma-
separated list of the services they use. Your output should look like this:
name | services
---------------+-------------------------------------------------------------------------
Pat Johnson | Unix Hosting, DNS, Whois Registration
Nancy Monreal |
Lynn Blake | DNS, Whois Registration, High Bandwidth, Business Support, Unix Hosting
Chen Ke-Hua | High Bandwidth, Unix Hosting
Scott Lakso | DNS, Dedicated Hosting, Unix Hosting
Jim Pornot | Unix Hosting, Dedicated Hosting, Bulk Email
(6 rows)
SELECT customers.name,
string_agg(services.description, ', ') AS "services"
FROM customers LEFT JOIN customers_services
ON customers.id = customer_id
LEFT JOIN services
ON service_id = services.id
GROUP BY customers.name;
name | services
---------------+-------------------------------------------------------------------------
Chen Ke-Hua | Unix Hosting, High Bandwidth
Jim Pornot | Unix Hosting, Dedicated Hosting, Bulk Email
Pat Johnson | Unix Hosting, DNS, Whois Registration
Lynn Blake | Unix Hosting, DNS, Whois Registration, High Bandwidth, Business Support
Scott Lakso | Unix Hosting, DNS, Dedicated Hosting
Nancy Monreal |
(6 rows)
-- Further Exploration
Can you modify the above command so the output looks like this?
name | description
---------------+--------------------
Chen Ke-Hua | High Bandwidth
| Unix Hosting
Jim Pornot | Dedicated Hosting
| Unix Hosting
| Bulk Email
Lynn Blake | Whois Registration
| High Bandwidth
| Business Support
| DNS
| Unix Hosting
Nancy Monreal |
Pat Johnson | Whois Registration
| DNS
| Unix Hosting
Scott Lakso | DNS
| Dedicated Hosting
| Unix Hosting
(17 rows)
This won''t be easy! Hint: you will need to use the window lag function together
with a CASE condition in your SELECT. To get you started, try this command:
SELECT customers.name,
lag(customers.name)
OVER (ORDER BY customers.name)
AS previous,
services.description
FROM customers
LEFT OUTER JOIN customers_services
ON customer_id = customers.id
LEFT OUTER JOIN services
ON services.id = service_id;
Examine the relationship between the previous column and the rest of the table
to get a handle on what lag does.
name | previous | description
---------------+---------------+--------------------
Chen Ke-Hua | | High Bandwidth
Chen Ke-Hua | Chen Ke-Hua | Unix Hosting
Jim Pornot | Chen Ke-Hua | Dedicated Hosting
Jim Pornot | Jim Pornot | Unix Hosting
Jim Pornot | Jim Pornot | Bulk Email
Lynn Blake | Jim Pornot | Whois Registration
Lynn Blake | Lynn Blake | High Bandwidth
Lynn Blake | Lynn Blake | Business Support
Lynn Blake | Lynn Blake | DNS
Lynn Blake | Lynn Blake | Unix Hosting
Nancy Monreal | Lynn Blake |
Pat Johnson | Nancy Monreal | Whois Registration
Pat Johnson | Pat Johnson | DNS
Pat Johnson | Pat Johnson | Unix Hosting
Scott Lakso | Pat Johnson | DNS
Scott Lakso | Scott Lakso | Dedicated Hosting
Scott Lakso | Scott Lakso | Unix Hosting
(17 rows)
SELECT CASE
WHEN customers.name = lag(customers.name)
OVER (ORDER BY customers.name)
THEN ''
ELSE customers.name
END,
services.description
FROM customers
LEFT OUTER JOIN customers_services
ON customers.id = customer_id
LEFT OUTER JOIN services
ON service_id = services.id;
name | description
---------------+--------------------
Chen Ke-Hua | High Bandwidth
| Unix Hosting
Jim Pornot | Dedicated Hosting
| Unix Hosting
| Bulk Email
Lynn Blake | Whois Registration
| High Bandwidth
| Business Support
| DNS
| Unix Hosting
Nancy Monreal |
Pat Johnson | Whois Registration
| DNS
| Unix Hosting
Scott Lakso | DNS
| Dedicated Hosting
| Unix Hosting
(17 rows)
|
-- t_action_linkage
DROP TABLE IF EXISTS t_action_linkage;
CREATE TABLE t_action_linkage
(
id bigint NOT NULL AUTO_INCREMENT,
dev_id char(36) NOT NULL COMMENT '设备id',
alarm_type bigint NOT NULL COMMENT '告警类型',
action_type tinyint(4) unsigned NOT NULL COMMENT '联动类型',
is_enable tinyint(1) unsigned NOT NULL COMMENT '是否使能',
add_time timestamp NOT NULL default CURRENT_TIMESTAMP,
update_time timestamp NOT NULL default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CONSTRAINT pk_t_action_linkage PRIMARY KEY (id),
CONSTRAINT uk_t_action_lingage UNIQUE (dev_id, alarm_type, action_type),
CONSTRAINT fk_t_action_linkage_dev_id FOREIGN KEY (dev_id)
REFERENCES t_device (id)
ON UPDATE CASCADE ON DELETE NO ACTION,
CONSTRAINT fk_t_action_linkage_alarm_type FOREIGN KEY (alarm_type)
REFERENCES t_alarm_type (alarm_type)
ON UPDATE CASCADE ON DELETE NO ACTION
)COMMENT= '联动业务表'; |
select * from award_amount_info where award_number like '001057-%' order by award_number,sequence_number;
create table award_amount_info_RRG as select * from award_amount_info where award_number = '001057-00001';
create table award_amount_info_RRG2 as select * from award_amount_info where award_number = '001057-00002';
select * from award_amount_info_RRG2;
insert into award_amount_info (
"ANTICIPATED_CHANGE_DIRECT",
"ANTICIPATED_CHANGE_INDIRECT",
"ANTICIPATED_TOTAL_DIRECT",
"ANTICIPATED_TOTAL_INDIRECT",
"OBLIGATED_TOTAL_DIRECT",
"OBLIGATED_TOTAL_INDIRECT",
"VER_NBR",
"TNM_DOCUMENT_NUMBER",
"AWARD_AMOUNT_INFO_ID",
"AWARD_ID",
"AWARD_NUMBER",
"SEQUENCE_NUMBER",
"ANTICIPATED_TOTAL_AMOUNT",
"ANT_DISTRIBUTABLE_AMOUNT",
"FINAL_EXPIRATION_DATE",
"CURRENT_FUND_EFFECTIVE_DATE",
"AMOUNT_OBLIGATED_TO_DATE",
"OBLI_DISTRIBUTABLE_AMOUNT",
"OBLIGATION_EXPIRATION_DATE",
"TRANSACTION_ID",
"ENTRY_TYPE",
"EOM_PROCESS_FLAG",
"UPDATE_TIMESTAMP",
"UPDATE_USER",
"ANTICIPATED_CHANGE",
"OBLIGATED_CHANGE",
"OBLIGATED_CHANGE_DIRECT",
"OBLIGATED_CHANGE_INDIRECT",
"OBJ_ID",
"ORIGINATING_AWARD_VERSION"
)
select "ANTICIPATED_CHANGE_DIRECT",
"ANTICIPATED_CHANGE_INDIRECT",
"ANTICIPATED_TOTAL_DIRECT",
"ANTICIPATED_TOTAL_INDIRECT",
"OBLIGATED_TOTAL_DIRECT",
"OBLIGATED_TOTAL_INDIRECT",
"VER_NBR",
"TNM_DOCUMENT_NUMBER",
"AWARD_AMOUNT_INFO_ID",
"AWARD_ID",
"AWARD_NUMBER",
"SEQUENCE_NUMBER",
"ANTICIPATED_TOTAL_AMOUNT",
"ANT_DISTRIBUTABLE_AMOUNT",
"FINAL_EXPIRATION_DATE",
"CURRENT_FUND_EFFECTIVE_DATE",
"AMOUNT_OBLIGATED_TO_DATE",
"OBLI_DISTRIBUTABLE_AMOUNT",
"OBLIGATION_EXPIRATION_DATE",
"TRANSACTION_ID",
"ENTRY_TYPE",
"EOM_PROCESS_FLAG",
"UPDATE_TIMESTAMP",
"UPDATE_USER",
"ANTICIPATED_CHANGE",
"OBLIGATED_CHANGE",
"OBLIGATED_CHANGE_DIRECT",
"OBLIGATED_CHANGE_INDIRECT",
"OBJ_ID",
"ORIGINATING_AWARD_VERSION"
from award_amount_info_rrg; |
USE Cine;
INSERT INTO Scripts
VALUES(6, 006, "Agregado de Capacidad", '2019_11_13');
ALTER TABLE Salas
ADD Capacidad INT NOT NULL;
UPDATE Salas SET Capacidad = 250 WHERE Codigo = 1;
UPDATE Salas SET Capacidad = 350 WHERE Codigo = 2;
UPDATE Salas SET Capacidad = 200 WHERE Codigo = 3;
UPDATE Salas SET Capacidad = 180 WHERE Codigo = 4;
UPDATE Salas SET Capacidad = 400 WHERE Codigo = 5;
UPDATE Salas SET Capacidad = 500 WHERE Codigo = 6;
|
--- Assignment 3: SQL DDL and Updates
--- 1 Give a 10% hike to all instructors
UPDATE instructor
SET salary = salary * (110 / 100);
--- 2 For all instructors who are advisors of atleast 2 students increase salary by 5000
UPDATE instructor AS ins,
(SELECT i_ID
FROM advisor
GROUP BY i_ID
HAVING COUNT(s_ID) >= 2) AS idash)
SET ins.salary = ins.salary
WHERE ins.ID = idash.i_ID;
--- B: DDL and DML statements for the following
--- 1 Each offering of a course (i.e. a section) can have many Teaching assistants; each teaching assistant is a student. Extend the existing schema(Add/Alter tables) to accommodate this requirement.
CREATE TABLE teaching_assistant
(ID VARCHAR(5),
course_id VARCHAR(8),
sec_id VARCHAR(8),
semester VARCHAR(6),
year DECIMAL(4, 0),
PRIMARY KEY (ID, course_id, sec_id, semester, year),
FOREIGN KEY (ID) REFERENCES student(ID) ON DELETE CASCADE,
FOREIGN KEY (course_id, sec_id, semester, year) REFERENCES section(course_id, sec_id, semester, year) ON DELETE CASCADE);
--- 2 According to the existing schema, one student can have only one advisor. Alter the schema to allow a student to have multiple advisors and make sure that you are able to insert multiple advisors for a student.
ALTER TABLE advisor
DROP PRIMARY KEY,
DROP FOREIGN KEY advisor_ibfk_1,
DROP FOREIGN KEY advisor_ibfk_2,
ADD PRIMARY KEY(s_id, i_id),
ADD FOREIGN KEY(s_id) REFERENCES student(ID),
ADD FOREIGN KEY(i_id) REFERENCES instructor(ID);
--- 3 Write SQL queries on the modified schema. You will need to insert data to ensure the query results are not empty.
--- Adding Data
INSERT INTO instructor (ID, name, dept_name, salary) VALUES ('77777', 'Ashok', 'Physics', 50000);
INSERT INTO advisor (s_ID, i_ID) VALUES ('12345', '77777');
INSERT INTO advisor (s_ID, i_ID) VALUES ('12345', '45565');
INSERT INTO advisor (s_ID, i_ID) VALUES ('12345', '83821');
--- Find all students who have more than 3 advisors
SELECT s.name
FROM student as s INNER JOIN advisor as a
ON s.ID = a.s_ID
GROUP BY s.ID
HAVING COUNT(*) > 3;
--- Find all students who are co-advised by Prof. Srinivas and Prof. Ashok.
SELECT s.name
FROM instructor as i1 INNER JOIN advisor as a1 INNER JOIN student as s INNER JOIN advisor as a2 INNER JOIN instructor as i2
ON i1.ID = a1.i_ID AND a1.s_ID = s.ID AND s.ID = a2.s_ID AND a2.i_ID = i2.ID
WHERE i1.name = "Srinivasan" AND i2.name = "Ashok";
--- Find students advised by instructors from different departments. etc.
SELECT DISTINCT s.name
FROM instructor as i1 INNER JOIN advisor as a1 INNER JOIN student as s INNER JOIN advisor as a2 INNER JOIN instructor as i2
ON i1.ID = a1.i_ID AND a1.s_ID = s.ID AND s.ID = a2.s_ID AND a2.i_ID = i2.ID
WHERE NOT(i1.dept_name = i2.dept_name);
--- 3 Write SQL Queries for the following
--- Delete all information in the database which is more than 10 years old. Add data as necessary to verify your query.
--- Delete the course CS 101. Any course which has CS 101 as a prereq should remove CS 101 from its prereq set. Create a cascade constraint to enforce the above rule, and verify that it is working.
SHOW CREATE TABLE prereq;
ALTER TABLE prereq
DROP FOREIGN KEY prereq_ibfk_2,
ADD FOREIGN KEY (prereq_id) REFERENCES course(course_id) ON DELETE CASCADE;
DELETE
FROM course
WHERE course_id = "CS-101";
|
ALTER TABLE CONTACT_USAGE
ADD CONSTRAINT FK_CONTACT_TYPE_CODE
FOREIGN KEY (CONTACT_TYPE_CODE)
REFERENCES CONTACT_TYPE (CONTACT_TYPE_CODE)
/
ALTER TABLE CONTACT_USAGE
ADD CONSTRAINT FK2_MODULE_CODE
FOREIGN KEY (MODULE_CODE)
REFERENCES COEUS_MODULE (MODULE_CODE)
/
|
drop materialized view if exists ofec_communication_cost_mv_tmp;
create materialized view ofec_communication_cost_mv_tmp as
select
row_number() over () as idx,
*,
s_o_cand_id as cand_id,
org_id as cmte_id,
report_pdf_url(image_num) as pdf_url
from fec_vsum_f76_vw
where extract(year from communication_dt)::integer >= :START_YEAR
;
create unique index on ofec_communication_cost_mv_tmp (sub_id);
create index on ofec_communication_cost_mv_tmp (cmte_id);
create index on ofec_communication_cost_mv_tmp (cand_id);
create index on ofec_communication_cost_mv_tmp (s_o_cand_office_st);
create index on ofec_communication_cost_mv_tmp (s_o_cand_office_district);
create index on ofec_communication_cost_mv_tmp (s_o_cand_office);
create index on ofec_communication_cost_mv_tmp (s_o_ind);
create index on ofec_communication_cost_mv_tmp (communication_dt);
create index on ofec_communication_cost_mv_tmp (communication_cost);
create index on ofec_communication_cost_mv_tmp (communication_tp);
create index on ofec_communication_cost_mv_tmp (communication_class);
create index on ofec_communication_cost_mv_tmp (image_num);
create index on ofec_communication_cost_mv_tmp (filing_form); |
select * from VozaciVozila;
select * from TramvajskeLinije;
select * from AutobuskeLinije;
select * from TrolejbuskeLinije;
select * from AutobuskeTramvajskeStanice;
select * from AutobuskeTrolejbuskeStanice;
select avg(godina) as ProsjekGodina from Vozaci;
select avg(2015 - godina_zaposlenja) as ProsjekGodinaRada from Vozaci;
select ime, prezime, max(Vozaci.godina) from Vozaci;
select * from StanicaIlidza;
select * from LinijaOtokaDobrinja;
select * from Tramvaj2;
select * from VozacLinije1I11;
select * from PrvaSmjena;
select * from PrvaSmjenaAutobusi;
select * from Vozac8PolazneStanice; |
```
CREATE TABLE `salaries` (
`emp_no` int(11) NOT NULL,
`salary` int(11) NOT NULL,
`from_date` date NOT NULL,
`to_date` date NOT NULL,
PRIMARY KEY (`emp_no`,`from_date`));
CREATE TABLE IF NOT EXISTS "titles" (
`emp_no` int(11) NOT NULL,
`title` varchar(50) NOT NULL,
`from_date` date NOT NULL,
`to_date` date DEFAULT NULL);
```
```
SELECT t.title,AVG(s.salary) as avg
FROM titles t
INNER JOIN salaries s
ON t.emp_no=s.emp_no
WHERE s.to_date='9999-01-01'
AND t.to_date='9999-01-01'
GROUP BY t.title
``` |
PARAMETERS [@ProductoID] Text (255);
SELECT A.ProductoID,
A.CategoriaContableID,
C.CategoriaContableNombre,
A.CategoriaFundoID,
D.CategoriaFundoNombre,
A.IngredienteActivo,
A.NombreComercial,
A.ProductoCodigo,
A.UnidadID,
B.UnidadNombre,
A.DosisHA,
A.LMR,
A.CategoriaID,
E.Categoria
FROM ((((TB_Producto AS A
LEFT JOIN TB_Unidades AS B ON A.UnidadId=B.UnidadID)
LEFT JOIN TB_ProductoCategoriaContable AS C ON A.CategoriaContableID=C.CategoriaContableID)
LEFT JOIN TB_ProductoCategoriaFundo AS D ON A.CategoriaFundoID=D.CategoriaFundoID)
LEFT JOIN K_ProductoSegmento AS E ON A.CategoriaID=E.CategoriaID)
WHERE A.ProductoID=[@ProductoID] OR [@ProductoID] IS NULL;
|
drop table bad_rows;
create table bad_rows (row_id ROWID
,oracle_error_code number);
undefine lob_column
undefine table_owner
undefine table_with_lob
set concat off
set serveroutput on
declare
n number;
error_code number;
bad_rows number := 0;
ora600 EXCEPTION;
PRAGMA EXCEPTION_INIT(ora600, -600);
begin
for cursor_lob in (select rowid rid, &&lob_column from &&table_owner.&table_with_lob) loop
begin
n:=dbms_lob.instr(cursor_lob.&&lob_column,hextoraw('889911')) ;
exception
when ora600 then
bad_rows := bad_rows + 1;
insert into bad_rows values(cursor_lob.rid,600);
commit;
when others then
error_code:=SQLCODE;
bad_rows := bad_rows + 1;
insert into bad_rows values(cursor_lob.rid,error_code);
commit;
end;
end loop;
dbms_output.put_line('Total Rows identified with errors in LOB column:'||bad_rows);
end;
/
select * from bad_rows; |
/* Formatted on 21/07/2014 18:41:45 (QP5 v5.227.12220.39754) */
CREATE OR REPLACE FORCE VIEW MCRE_OWN.V_MCRES_APP_COMUNIC_SCADEN
(
COD_ABI,
COD_NDG,
COD_SNDG,
DESC_SCADENZA,
DTA_SCADENZA,
VAL_GG_SCADENZA,
COD_TIPO_SCADENZA,
FLG_LINK,
DESC_ISTITUTO,
DESC_NOME_CONTROPARTE,
COD_PRESIDIO,
DESC_PRESIDIO,
COD_LIVELLO,
COD_UO_PRATICA,
COD_MATR_PRATICA
)
AS
SELECT DISTINCT
-- Scadenza ipoteca
-- 20130218 AG parametrizzazione di val_limite_scadenza
g.cod_abi,
g.cod_ndg,
g.cod_sndg,
s.desc_scadenza,
ADD_MONTHS (g.dta_scadenza_garanzia, s.val_limite_scadenza)
dta_scadenza,
ADD_MONTHS (g.dta_scadenza_garanzia, s.val_limite_scadenza)
- TRUNC (SYSDATE)
val_gg_scadenza,
s.cod_tipo_scadenza,
0 flg_link,
i.desc_istituto,
gg.desc_nome_controparte,
p.cod_presidio,
p.desc_presidio,
p.cod_livello,
z.cod_uo_pratica,
z.cod_matr_pratica
FROM t_mcres_app_garanzie g,
t_mcres_app_scadenzario s,
t_mcres_app_pratiche z,
t_mcres_app_istituti i,
t_mcre0_app_anagrafica_gruppo gg,
(SELECT *
FROM v_mcres_app_lista_presidi
WHERE cod_tipo = 'P') p
WHERE z.flg_attiva = 1
AND g.cod_abi = z.cod_abi
AND g.cod_ndg = z.cod_ndg
AND g.cod_abi = i.cod_abi
AND g.cod_sndg = gg.cod_sndg
AND z.cod_uo_pratica = p.cod_presidio(+)
AND s.cod_tipo_scadenza = 1
AND (ADD_MONTHS (g.dta_scadenza_garanzia, s.val_limite_scadenza) BETWEEN TRUNC (
SYSDATE)
- s.val_gg_prec
AND TRUNC (
SYSDATE)
+ s.val_gg_succ -- add_months(g.dta_scadenza_garanzia,240) between trunc(sysdate) and
-- trunc(sysdate) +s.val_gg_succ
-- or add_months(g.dta_scadenza_garanzia,240) between trunc(sysdate)-
-- s.val_gg_prec and trunc(sysdate)
)
AND g.cod_forma_tecnica = '08070'
---------------------
UNION ALL
---------------------
--valutazione rapporto
-- SELECT DISTINCT
-- r.cod_abi,
-- r.cod_ndg,
-- r.cod_sndg,
-- s.desc_scadenza,
-- ADD_MONTHS (r.dta_nbv, s.val_limite_scadenza) dta_scadenza,
-- ADD_MONTHS (r.dta_nbv, s.val_limite_scadenza) - TRUNC (SYSDATE)
-- val_gg_scadenza,
-- cod_tipo_scadenza,
-- CASE
-- WHEN ADD_MONTHS (r.dta_nbv, s.val_limite_scadenza) >=
-- TRUNC (SYSDATE)
-- THEN
-- 1
-- ELSE
-- 0
-- END
-- flg_link,
-- i.desc_istituto,
-- g.desc_nome_controparte,
-- p.cod_presidio,
-- p.desc_presidio,
-- p.cod_livello,
-- z.cod_uo_pratica,
-- z.cod_matr_pratica
-- FROM t_mcres_app_rapporti r,
-- t_mcres_app_scadenzario s,
-- t_mcres_app_pratiche z,
-- t_mcres_app_istituti i,
-- t_mcre0_app_anagrafica_gruppo g,
-- (SELECT *
-- FROM v_mcres_app_lista_presidi
-- WHERE cod_tipo = 'P') p
-- WHERE z.flg_attiva = 1
-- AND z.cod_abi = r.cod_abi
-- AND z.cod_ndg = r.cod_ndg
-- AND z.cod_abi = i.cod_abi
-- AND z.cod_sndg = g.cod_sndg
-- AND z.cod_uo_pratica = p.cod_presidio(+)
-- AND s.cod_tipo_scadenza = 2
-- AND r.dta_nbv BETWEEN ADD_MONTHS (TRUNC (SYSDATE) - s.val_gg_prec,-s.val_limite_scadenza) AND ADD_MONTHS (TRUNC (SYSDATE) + s.val_gg_succ, -s.val_limite_scadenza)
-- AND NOT EXISTS
-- (SELECT DISTINCT 1
-- FROM t_mcres_app_delibere d
-- WHERE d.cod_abi = r.cod_abi
-- AND d.cod_ndg = r.cod_ndg
-- AND d.cod_delibera = 'RW'
-- AND d.cod_stato_delibera = 'CO')
SELECT a.cod_abi,
a.cod_ndg,
a.cod_sndg,
s.desc_scadenza,
ADD_MONTHS (NVL (a.DTA_CONFERMA, a.DTA_AGGIORNAMENTO_DELIBERA),
s.val_limite_scadenza)
dta_scadenza,
ADD_MONTHS (NVL (a.DTA_CONFERMA, a.DTA_AGGIORNAMENTO_DELIBERA),
s.val_limite_scadenza)
- TRUNC (SYSDATE)
val_gg_scadenza,
cod_tipo_scadenza,
CASE
WHEN ADD_MONTHS (
NVL (a.DTA_CONFERMA, a.DTA_AGGIORNAMENTO_DELIBERA),
s.val_limite_scadenza) >= TRUNC (SYSDATE)
THEN
1
ELSE
0
END
flg_link,
i.desc_istituto,
g.desc_nome_controparte,
p.cod_presidio,
p.desc_presidio,
p.cod_livello,
z.cod_uo_pratica,
z.cod_matr_pratica
FROM ( SELECT cod_abi,
cod_ndg,
cod_sndg,
MAX (DTA_CONFERMA) DTA_CONFERMA,
MAX (DTA_AGGIORNAMENTO_DELIBERA) DTA_AGGIORNAMENTO_DELIBERA,
MAX (DTA_INSERIMENTO_DELIBERA) DTA_INSERIMENTO_DELIBERA
FROM t_mcres_app_delibere
WHERE cod_delibera IN ('NS', 'RV', 'AS', 'RW')
AND cod_stato_delibera = 'CO'
GROUP BY cod_abi, cod_ndg, cod_sndg) a,
t_mcres_app_scadenzario s,
t_mcres_app_pratiche z,
t_mcres_app_istituti i,
t_mcre0_app_anagrafica_gruppo g,
(SELECT *
FROM v_mcres_app_lista_presidi
WHERE cod_tipo = 'P') p
WHERE 1 = 1
AND z.flg_attiva = 1
AND a.cod_abi = z.cod_abi
AND a.cod_ndg = z.cod_ndg
AND a.cod_abi = i.cod_abi
AND z.cod_sndg = g.cod_sndg
AND z.cod_uo_pratica = p.cod_presidio(+)
AND s.cod_tipo_scadenza = 2
AND 1 =
NVL (
(SELECT DISTINCT
CASE
WHEN COD_STATO_DELIBERA != 'CO'
THEN
0
WHEN COD_STATO_DELIBERA = 'CO'
THEN
CASE
WHEN cod_delibera = 'SN'
THEN
0
WHEN cod_delibera IN ('TP', 'TT')
AND DTA_AGGIORNAMENTO_DELIBERA >
SYSDATE
THEN
1
WHEN cod_delibera = 'TS'
AND DTA_CONFERMA <
ADD_MONTHS (
SYSDATE,
-VAL_LIMITE_SCADENZA)
THEN
1
ELSE
0
END
WHEN COD_STATO_DELIBERA = 'AD'
THEN
CASE
WHEN cod_delibera = 'TT'
THEN
0
WHEN cod_delibera IN ('TP', 'TS')
AND DTA_AGGIORNAMENTO_DELIBERA <
ADD_MONTHS (
SYSDATE,
-VAL_LIMITE_SCADENZA)
THEN
1
ELSE
0
END
WHEN COD_STATO_DELIBERA = 'NA'
THEN
CASE
WHEN DTA_CONFERMA <
ADD_MONTHS (
SYSDATE,
-VAL_LIMITE_SCADENZA)
THEN
1
ELSE
0
END
ELSE
0
END
FROM t_mcres_app_delibere b
WHERE b.cod_abi = a.cod_abi
AND b.cod_ndg = a.cod_ndg
AND b.cod_delibera IN ('TT', 'TS', 'TP', 'SN')
AND b.DTA_INSERIMENTO_DELIBERA >=
a.DTA_INSERIMENTO_DELIBERA
AND b.DTA_INSERIMENTO_DELIBERA >=
ADD_MONTHS (SYSDATE, -VAL_LIMITE_SCADENZA)),
1);
|
INSERT INTO `burgers_db`.`burgers` (`burger_name`) VALUES ('Big Mac');
INSERT INTO `burgers_db`.`burgers` (`burger_name`) VALUES ('Mc Chicken');
INSERT INTO `burgers_db`.`burgers` (`burger_name`) VALUES ('Mc Double');
|
INSERT INTO cloth_full (vendor_code,
sort,
weaving_pattern,
decoration_pattern,
color,
length,
arrival_date,
podgr_pattern,
cloth
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) |
-- ----------------------------
-- TRUNCATE Table PERSON_HOBBY
-- ----------------------------
TRUNCATE TABLE person_hobby;
-- ----------------------------
-- TRUNCATE Table PERSON
-- ----------------------------
TRUNCATE TABLE person;
-- ----------------------------
-- TRUNCATE Table colour
-- ----------------------------
TRUNCATE TABLE colour;
-- ----------------------------
-- TRUNCATE Tabl hobby
-- ----------------------------
TRUNCATE TABLE hobby;
-- ----------------------------
-- Records of colour
-- ----------------------------
INSERT INTO colour VALUES ('00298aa3-17ff-4f4a-a647-1fd06e4caab7', 'System User', '2020-01-21 15:40:25.06', true, 'System User', '2020-01-21 15:40:25.06', '#FF00FF', 'Magenta');
INSERT INTO colour VALUES ('029dc82b-568a-447f-ad76-d0c2c187bed0', 'System User', '2020-01-21 15:40:24.272', true, 'System User', '2020-01-21 15:40:24.272', '#9932CC', 'Dark Orchid');
INSERT INTO colour VALUES ('05707ab1-9b61-4e71-9a22-dd3402cf15d6', 'System User', '2020-01-21 15:40:25.09', true, 'System User', '2020-01-21 15:40:25.09', '#800000', 'Web Maroon');
INSERT INTO colour VALUES ('0678478f-e1f6-4c2d-a42e-11f2a52bfea5', 'System User', '2020-01-21 15:40:25.136', true, 'System User', '2020-01-21 15:40:25.136', '#BA55D3', 'Medium Orchid');
INSERT INTO colour VALUES ('09d5afe2-5b4f-4d72-9057-c1aeb4690894', 'System User', '2020-01-21 15:40:24.171', true, 'System User', '2020-01-21 15:40:24.171', '#B8860B', 'Dark Goldenrod');
INSERT INTO colour VALUES ('0a387b34-7bd2-4278-8a86-236d2b9a2beb', 'System User', '2020-01-21 15:40:24.769', true, 'System User', '2020-01-21 15:40:24.769', '#FFF0F5', 'Lavender Blush');
INSERT INTO colour VALUES ('0b3db7e0-9c4c-4936-98e0-24ef27fd5824', 'System User', '2020-01-21 15:40:24.619', true, 'System User', '2020-01-21 15:40:24.619', '#00FF00', 'Green');
INSERT INTO colour VALUES ('0bf492da-4845-41fa-961d-e25174b51861', 'System User', '2020-01-21 15:40:24.496', true, 'System User', '2020-01-21 15:40:24.496', '#228B22', 'Forest Green');
INSERT INTO colour VALUES ('10b00fc3-0b88-402e-8beb-b2ea9edb0957', 'System User', '2020-01-21 15:40:24.697', true, 'System User', '2020-01-21 15:40:24.697', '#CD5C5C', 'Indian Red');
INSERT INTO colour VALUES ('11487744-da45-4a86-ac2e-e70075179d6f', 'System User', '2020-01-21 15:40:24.213', true, 'System User', '2020-01-21 15:40:24.213', '#BDB76B', 'Dark Khaki');
INSERT INTO colour VALUES ('119a0274-2956-48c3-959d-a212580cb640', 'System User', '2020-01-21 15:40:25.393', true, 'System User', '2020-01-21 15:40:25.393', '#DA70D6', 'Orchid');
INSERT INTO hobby VALUES ('fba2f4e2-9dff-421b-9696-c6e3fa77653b', 'System User', '2020-01-21 15:40:35.932', true, 'System User', '2020-01-21 15:40:35.932', 'TV watching');
INSERT INTO hobby VALUES ('fbc0b795-9f64-4f3c-b046-343bbc361e1f', 'System User', '2020-01-21 15:40:30.368', true, 'System User', '2020-01-21 15:40:30.368', 'Arts');
INSERT INTO hobby VALUES ('fc3bd2fd-a598-4178-9bc1-3f8e00969650', 'System User', '2020-01-21 15:40:32.459', true, 'System User', '2020-01-21 15:40:32.459', 'Frisbee Golf');
INSERT INTO hobby VALUES ('fc408efd-1453-41ec-a6c7-d31043aa5eb3', 'System User', '2020-01-21 15:40:34.545', true, 'System User', '2020-01-21 15:40:34.545', 'Radio-controlled car racing');
INSERT INTO hobby VALUES ('fc67a7dd-9b28-4e90-aa77-b2b632c48ae7', 'System User', '2020-01-21 15:40:35.847', true, 'System User', '2020-01-21 15:40:35.847', 'Trainspotting');
INSERT INTO hobby VALUES ('fd24a41a-ee13-496f-b9d3-a7ee3d4750c7', 'System User', '2020-01-21 15:40:35.901', true, 'System User', '2020-01-21 15:40:35.901', 'Triathlon');
INSERT INTO hobby VALUES ('fd2f4608-de5c-46a0-b920-462519ad2651', 'System User', '2020-01-21 15:40:36.127', true, 'System User', '2020-01-21 15:40:36.127', 'Walking');
INSERT INTO hobby VALUES ('fda13e34-08c5-4eb5-8914-4f06f8876664', 'System User', '2020-01-21 15:40:27.924', true, 'System User', '2020-01-21 15:40:27.924', 'Spider');
INSERT INTO hobby VALUES ('fe39ae2c-b4ed-490b-9a57-c48a3d515685', 'System User', '2020-01-21 15:40:29.641', true, 'System User', '2020-01-21 15:40:29.641', 'Wines');
INSERT INTO hobby VALUES ('fe7dd1f7-17a0-411e-ab26-e198fbb3e476', 'System User', '2020-01-21 15:40:33.536', true, 'System User', '2020-01-21 15:40:33.536', 'Leathercrafting');
INSERT INTO hobby VALUES ('fe94229b-b5ce-4481-8b82-4782d73e5ce8', 'System User', '2020-01-21 15:40:32.47', true, 'System User', '2020-01-21 15:40:32.47', 'Gambling');
INSERT INTO hobby VALUES ('ff0ab6bf-23d1-4351-bb99-d76f3749402e', 'System User', '2020-01-21 15:40:30.008', true, 'System User', '2020-01-21 15:40:30.008', 'real time games');
INSERT INTO hobby VALUES ('ff1d3aa4-0f34-4a44-829f-a0829edac2e2', 'System User', '2020-01-21 15:40:33.765', true, 'System User', '2020-01-21 15:40:33.765', 'Metal detecting');
INSERT INTO hobby VALUES ('ff8bfd25-6a2b-4629-8a80-83de59ea554c', 'System User', '2020-01-21 15:40:35.146', true, 'System User', '2020-01-21 15:40:35.146', 'Singing In Choir');
INSERT INTO hobby VALUES ('ffa1c1eb-0107-4476-826f-3f6b5b559720', 'System User', '2020-01-21 15:40:28.552', true, 'System User', '2020-01-21 15:40:28.552', 'Texting') |
CREATE OR REPLACE VIEW GW_MIGRA_NETAQUA.TMP_V_EDIT_ELEMENT_AIXETA AS
SELECT 'AIX_1_' || T1.ID_FONT element_id,
'AIX_1_' || T1.ID_FONT code,
CASE
WHEN (AIXETA IS NULL OR AIXETA = 'AL') AND (AIX_ROSC IS NULL OR AIX_ROSC = 0) THEN 'AIX_XX'
WHEN (AIXETA IS NULL OR AIXETA = 'AL') AND (AIX_ROSC = .5) THEN 'AIX_XX_1/2'
WHEN AIXETA IS NULL OR AIXETA = 'AL' THEN 'AIX_XX_' || AIX_ROSC
WHEN AIX_ROSC IS NULL OR AIX_ROSC = 0 THEN 'AIX_' || TRIM(SUBSTR(T2.FONT_AIXETA, INSTR(T2.FONT_AIXETA,' - ')+3))
WHEN AIX_ROSC = .5 THEN 'AIX_' || TRIM(SUBSTR(T2.FONT_AIXETA, INSTR(T2.FONT_AIXETA,' - ')+3)) || '_1/2'
ELSE 'AIX_' || TRIM(SUBSTR(T2.FONT_AIXETA, INSTR(T2.FONT_AIXETA,' - ')+3)) || '_' || AIX_ROSC
END elementcat_id,
'AIXETA' elementtype_id,
null serial_number,
CASE T1.ESTAT
WHEN 'A' THEN 1
WHEN 'B' THEN 0
ELSE -1
END state,
CAST(null AS SMALLINT) state_type,
TO_NUMBER(T1.AIX_NUME) num_elements,
null observ,
null "comment",
null function_type,
null category_type,
null location_type,
null fluid_type,
null workcat_id,
null workcat_id_end,
null buildercat_id,
CAST(null AS DATE) builtdate,
CAST(null AS DATE) enddate,
null ownercat_id,
0 rotation,
'-' link,
null verified,
null the_geom,
null label_x,
null label_y,
0 label_rotation,
'true' publish,
'true' inventory,
null undelete,
1 expl_id
FROM NA_MATARO.NA_V_FONT T1
LEFT JOIN NA_MATARO.CAT2_T_FONT_AIXETA T2 ON T1.AIXETA = T2.ID_FONT_AIXETA
WHERE AIXETA IS NOT NULL OR AIX_ROSC IS NOT NULL OR AIX_NUME IS NOT NULL;
CREATE OR REPLACE VIEW GW_MIGRA_NETAQUA.TMP_V_EDIT_ELEMENT_ARQFONT AS
SELECT 'ARF_1_' || T1.ID_FONT element_id,
'ARF_1_' || T1.ID_FONT code,
CASE
WHEN ARQ_SECC='C' THEN ARQ_MATE || '_' || ARQ_SECC || '_' || ARQ_DIAM
WHEN ARQ_SECC='Q' THEN ARQ_MATE || '_' || ARQ_SECC || '_' || ARQ_AMP || 'x' || ARQ_ALT
WHEN ARQ_SECC='R' THEN ARQ_MATE || '_' || ARQ_SECC || '_' || ARQ_AMP || 'x' || ARQ_ALT
ELSE ARQ_MATE || '_' || 'X'
END elementcat_id,
'ARQFONT' elementtype_id,
null serial_number,
CASE T1.ESTAT
WHEN 'A' THEN 1
WHEN 'B' THEN 0
ELSE -1
END state,
CAST(null AS SMALLINT) state_type,
null num_elements,
null observ,
null "comment",
null function_type,
null category_type,
null location_type,
null fluid_type,
null workcat_id,
null workcat_id_end,
null buildercat_id,
CAST(null AS DATE) builtdate,
CAST(null AS DATE) enddate,
null ownercat_id,
0 rotation,
'-' link,
null verified,
null the_geom,
null label_x,
null label_y,
0 label_rotation,
'true' publish,
'true' inventory,
null undelete,
1 expl_id
FROM NA_MATARO.NA_V_FONT T1
WHERE ARQ_SECC IS NOT NULL OR ARQ_MATE IS NOT NULL OR ARQ_SECC IS NOT NULL OR ARQ_DIAM IS NOT NULL;
CREATE OR REPLACE VIEW GW_MIGRA_NETAQUA.TMP_V_EDIT_ELEMENT_PORTELLA AS
SELECT 'POR1_1_' || T1.ID_ESCO element_id,
'POR1_1_' || T1.ID_ESCO code,
CASE
WHEN T2.ID IS NULL THEN 'PORT_XX'
ELSE T2.ID
END elementcat_id,
'PORTELLA' elementtype_id,
null serial_number,
CASE T1.ESTAT
WHEN 'A' THEN 1
WHEN 'B' THEN 0
ELSE -1
END state,
CAST(null AS SMALLINT) state_type,
null num_elements,
CASE
WHEN T2.ID IS NULL THEN TRIM(T1.MAT1 || ' ' || T1.MID1)
ELSE null
END observ,
null "comment",
null function_type,
null category_type,
T1.SIT1 location_type,
null fluid_type,
null workcat_id,
null workcat_id_end,
null buildercat_id,
CAST(null AS DATE) builtdate,
CAST(null AS DATE) enddate,
null ownercat_id,
0 rotation,
'-' link,
null verified,
null the_geom,
null label_x,
null label_y,
0 label_rotation,
'true' publish,
'true' inventory,
null undelete,
1 expl_id
FROM NA_MATARO.NA_V_ESCO T1
LEFT JOIN TMP_CAT_ELEMENT_PORTELLA T2 ON T1.MAT1 = T2.MATCAT_ID AND T1.MID1 = T2.GEOMETRY AND T2.ELEMENTTYPE_ID = 'PORTELLA'
WHERE T1.MAT1 IS NOT NULL OR T1.MID1 IS NOT NULL OR T1.SIT1 IS NOT NULL
UNION
SELECT 'POR2_1_' || T1.ID_ESCO element_id,
'POR2_1_' || T1.ID_ESCO code,
CASE
WHEN T2.ID IS NULL THEN 'PORT_XX'
ELSE T2.ID
END elementcat_id,
'PORTELLA' elementtype_id,
null serial_number,
CASE T1.ESTAT
WHEN 'A' THEN 1
WHEN 'B' THEN 0
ELSE -1
END state,
CAST(null AS SMALLINT) state_type,
null num_elements,
CASE
WHEN T2.ID IS NULL THEN TRIM(T1.MAT2 || ' ' || T1.MID2)
ELSE null
END observ,
null "comment",
null function_type,
null category_type,
T1.SIT2 location_type,
null fluid_type,
null workcat_id,
null workcat_id_end,
null buildercat_id,
CAST(null AS DATE) builtdate,
CAST(null AS DATE) enddate,
null ownercat_id,
0 rotation,
'-' link,
null verified,
null the_geom,
null label_x,
null label_y,
0 label_rotation,
'true' publish,
'true' inventory,
null undelete,
1 expl_id
FROM NA_MATARO.NA_V_ESCO T1
LEFT JOIN TMP_CAT_ELEMENT_PORTELLA T2 ON T1.MAT2 = T2.MATCAT_ID AND T1.MID2 = T2.GEOMETRY AND T2.ELEMENTTYPE_ID = 'PORTELLA'
WHERE T1.MAT2 IS NOT NULL OR T1.MID2 IS NOT NULL OR T1.SIT2 IS NOT NULL
UNION
SELECT 'POR3_1_' || T1.ID_ESCO element_id,
'POR3_1_' || T1.ID_ESCO code,
CASE
WHEN T2.ID IS NULL THEN 'PORT_XX'
ELSE T2.ID
END elementcat_id,
'PORTELLA' elementtype_id,
null serial_number,
CASE T1.ESTAT
WHEN 'A' THEN 1
WHEN 'B' THEN 0
ELSE -1
END state,
CAST(null AS SMALLINT) state_type,
null num_elements,
CASE
WHEN T2.ID IS NULL THEN TRIM(T1.MAT3 || ' ' || T1.MID3)
ELSE null
END observ,
null "comment",
null function_type,
null category_type,
T1.SIT3 location_type,
null fluid_type,
null workcat_id,
null workcat_id_end,
null buildercat_id,
CAST(null AS DATE) builtdate,
CAST(null AS DATE) enddate,
null ownercat_id,
0 rotation,
'-' link,
null verified,
null the_geom,
null label_x,
null label_y,
0 label_rotation,
'true' publish,
'true' inventory,
null undelete,
1 expl_id
FROM NA_MATARO.NA_V_ESCO T1
LEFT JOIN TMP_CAT_ELEMENT_PORTELLA T2 ON T1.MAT3 = T2.MATCAT_ID AND T1.MID3 = T2.GEOMETRY AND T2.ELEMENTTYPE_ID = 'PORTELLA'
WHERE T1.MAT3 IS NOT NULL OR T1.MID3 IS NOT NULL OR T1.SIT3 IS NOT NULL;
CREATE OR REPLACE VIEW GW_MIGRA_NETAQUA.TMP_V_EDIT_ELEMENT_ARQUETA AS
SELECT 'ARQ_1_' || T1.ID_VDES element_id,
'ARQ_1_' || T1.ID_VDES code,
CASE
WHEN ARQUETA = 'X-XX' AND MAT_TAPA IS NULL THEN 'X-XX'
WHEN ARQUETA = 'X-XX' AND MAT_TAPA = 'XX' THEN 'X-XX'
WHEN ARQUETA = 'X-XX' THEN 'X-' || MAT_TAPA
WHEN MAT_TAPA IS NULL THEN ARQUETA
WHEN MAT_TAPA = 'FO' THEN ARQUETA
ELSE ARQUETA || '_' || MAT_TAPA
END elementcat_id,
'ARQUETA' elementtype_id,
null serial_number,
CASE T1.ESTAT
WHEN 'A' THEN 1
WHEN 'B' THEN 0
ELSE -1
END state,
CAST(null AS SMALLINT) state_type,
null num_elements,
null observ,
null "comment",
null function_type,
null category_type,
null location_type,
null fluid_type,
null workcat_id,
null workcat_id_end,
null buildercat_id,
CAST(null AS DATE) builtdate,
CAST(null AS DATE) enddate,
null ownercat_id,
0 rotation,
'-' link,
null verified,
null the_geom,
null label_x,
null label_y,
0 label_rotation,
'true' publish,
'true' inventory,
null undelete,
1 expl_id
FROM NA_MATARO.NA_V_VDES T1
WHERE T1.ARQUETA IS NOT NULL OR T1.MAT_TAPA IS NOT NULL
UNION
SELECT 'ARQB_1_' || T1.ID_BINC element_id,
'ARQB_1_' || T1.ID_BINC code,
TRAPA elementcat_id,
'ARQUETA' elementtype_id,
null serial_number,
CASE T1.ESTAT
WHEN 'A' THEN 1
WHEN 'B' THEN 0
ELSE -1
END state,
CAST(null AS SMALLINT) state_type,
null num_elements,
null observ,
null "comment",
null function_type,
null category_type,
null location_type,
null fluid_type,
null workcat_id,
null workcat_id_end,
null buildercat_id,
CAST(null AS DATE) builtdate,
CAST(null AS DATE) enddate,
null ownercat_id,
0 rotation,
'-' link,
null verified,
null the_geom,
null label_x,
null label_y,
0 label_rotation,
'true' publish,
'true' inventory,
null undelete,
1 expl_id
FROM NA_MATARO.NA_V_BINC T1
WHERE T1.TRAPA IS NOT NULL
UNION
SELECT 'ARQV_1_' || T1.ID_VENT element_id,
'ARQV_1_' || T1.ID_VENT code,
TRAPA elementcat_id,
'ARQUETA' elementtype_id,
null serial_number,
CASE T1.ESTAT
WHEN 'A' THEN 1
WHEN 'B' THEN 0
ELSE -1
END state,
CAST(null AS SMALLINT) state_type,
null num_elements,
null observ,
null "comment",
null function_type,
null category_type,
null location_type,
null fluid_type,
null workcat_id,
null workcat_id_end,
null buildercat_id,
CAST(null AS DATE) builtdate,
CAST(null AS DATE) enddate,
null ownercat_id,
0 rotation,
'-' link,
null verified,
null the_geom,
null label_x,
null label_y,
0 label_rotation,
'true' publish,
'true' inventory,
null undelete,
1 expl_id
FROM NA_MATARO.NA_V_VENT T1
WHERE T1.TRAPA IS NOT NULL
UNION
SELECT 'ARQL_1_' || T1.ID_VALV element_id,
'ARQL_1_' || T1.ID_VALV code,
CASE T1.ARQUETA
WHEN 'AL' THEN 'X-XX'
ELSE T1.ARQUETA
END elementcat_id,
'ARQUETA' elementtype_id,
null serial_number,
CASE T1.ESTAT
WHEN 'A' THEN 1
WHEN 'B' THEN 0
ELSE -1
END state,
CAST(null AS SMALLINT) state_type,
null num_elements,
null observ,
null "comment",
null function_type,
null category_type,
null location_type,
null fluid_type,
null workcat_id,
null workcat_id_end,
null buildercat_id,
CAST(null AS DATE) builtdate,
CAST(null AS DATE) enddate,
null ownercat_id,
0 rotation,
'-' link,
null verified,
null the_geom,
null label_x,
null label_y,
0 label_rotation,
'true' publish,
'true' inventory,
null undelete,
1 expl_id
FROM NA_MATARO.NA_V_VALV T1
WHERE T1.ARQUETA IS NOT NULL;
CREATE OR REPLACE VIEW GW_MIGRA_NETAQUA.TMP_V_EDIT_ELEMENT_PLACA AS
SELECT 'PLA_1_' || T1.ID_BINC element_id,
'PLA_1_' || T1.ID_BINC code,
'PLA_XX' elementcat_id,
'PLACA' elementtype_id,
null serial_number,
CASE T1.ESTAT
WHEN 'A' THEN 1
WHEN 'B' THEN 0
ELSE -1
END state,
CAST(null AS SMALLINT) state_type,
null num_elements,
null observ,
null "comment",
null function_type,
null category_type,
CASE T1.UBI_PLACA
WHEN 'TANCA MET.' THEN 'TANCA'
ELSE T1.UBI_PLACA
END location_type,
null fluid_type,
null workcat_id,
null workcat_id_end,
null buildercat_id,
CAST(null AS DATE) builtdate,
CAST(null AS DATE) enddate,
null ownercat_id,
0 rotation,
'-' link,
null verified,
null the_geom,
null label_x,
null label_y,
0 label_rotation,
'true' publish,
'true' inventory,
null undelete,
1 expl_id
FROM NA_MATARO.NA_V_BINC T1
WHERE T1.UBI_PLACA IS NOT NULL;
CREATE OR REPLACE VIEW GW_MIGRA_NETAQUA.V_EDIT_ELEMENT AS
SELECT * FROM TMP_V_EDIT_ELEMENT_AIXETA
UNION
SELECT * FROM TMP_V_EDIT_ELEMENT_ARQFONT
UNION
SELECT * FROM TMP_V_EDIT_ELEMENT_ARQUETA
UNION
SELECT * FROM TMP_V_EDIT_ELEMENT_PORTELLA
UNION
SELECT * FROM TMP_V_EDIT_ELEMENT_PLACA;
|
-- 19/09/2014
UPDATE customers SET deleted = 1 WHERE customer_id IN (280,218,357,313,236,371,248,78,92,138,142,158,181);
UPDATE shipping_details SET customer_id = 261 WHERE customer_id IN(280);
UPDATE shipping_details SET customer_id = 365 WHERE customer_id IN(218, 357);
UPDATE shipping_details SET customer_id = 312 WHERE customer_id IN(313);
UPDATE shipping_details SET customer_id = 321 WHERE customer_id IN(236);
UPDATE shipping_details SET customer_id = 370 WHERE customer_id IN(371, 248);
UPDATE shipping_details SET customer_id = 77 WHERE customer_id IN(78);
UPDATE shipping_details SET customer_id = 309 WHERE customer_id IN(92);
UPDATE shipping_details SET customer_id = 307 WHERE customer_id IN(138);
UPDATE shipping_details SET customer_id = 275 WHERE customer_id IN(142);
UPDATE shipping_details SET customer_id = 355 WHERE customer_id IN(158);
UPDATE shipping_details SET customer_id = 304 WHERE customer_id IN(181);
ALTER TABLE `customers` ADD `total_paid` INT(11) AFTER `type_id`;
UPDATE customers c SET total_paid = (SELECT SUM(s.total) FROM shipping_details s WHERE s.customer_id = c.customer_id); |
/*
Warnings:
- You are about to drop the column `address` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `age` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `description` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `dob` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `education` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `facebookAccessToken` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `facebookRefreshToken` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `gender` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `googleId` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `industryId` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `isAdmin` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `isInvestor` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `isMentor` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `isModerator` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `isUser` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `password` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `phoneNumber` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `remember_token` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `title` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `user_type` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `user_type_value` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `website` on the `User` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "User" DROP COLUMN "address",
DROP COLUMN "age",
DROP COLUMN "description",
DROP COLUMN "dob",
DROP COLUMN "education",
DROP COLUMN "facebookAccessToken",
DROP COLUMN "facebookRefreshToken",
DROP COLUMN "gender",
DROP COLUMN "googleId",
DROP COLUMN "industryId",
DROP COLUMN "isAdmin",
DROP COLUMN "isInvestor",
DROP COLUMN "isMentor",
DROP COLUMN "isModerator",
DROP COLUMN "isUser",
DROP COLUMN "password",
DROP COLUMN "phoneNumber",
DROP COLUMN "remember_token",
DROP COLUMN "title",
DROP COLUMN "user_type",
DROP COLUMN "user_type_value",
DROP COLUMN "website";
-- CreateTable
CREATE TABLE "UserChallenge" (
"id" TEXT NOT NULL,
"challengeId" TEXT,
"userId" TEXT,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Challenge" (
"id" TEXT NOT NULL,
"name" VARCHAR(255) NOT NULL,
"description" VARCHAR(1000) NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"value" INTEGER NOT NULL,
"challengeStateId" TEXT NOT NULL,
"challengeCategoryId" TEXT NOT NULL,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ChallengeTag" (
"id" TEXT NOT NULL,
"label" VARCHAR(255) NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"challengeId" TEXT,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ChallengeNote" (
"id" TEXT NOT NULL,
"label" VARCHAR(255) NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"challengeId" TEXT,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ChallengeState" (
"id" TEXT NOT NULL,
"key" VARCHAR(255) NOT NULL,
"value" VARCHAR(255) NOT NULL,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ChallengeCategory" (
"id" TEXT NOT NULL,
"key" VARCHAR(255) NOT NULL,
"value" VARCHAR(255) NOT NULL,
PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "Challenge.id_unique" ON "Challenge"("id");
-- CreateIndex
CREATE UNIQUE INDEX "ChallengeTag.id_unique" ON "ChallengeTag"("id");
-- CreateIndex
CREATE UNIQUE INDEX "ChallengeNote.id_unique" ON "ChallengeNote"("id");
-- CreateIndex
CREATE UNIQUE INDEX "ChallengeState.id_unique" ON "ChallengeState"("id");
-- CreateIndex
CREATE UNIQUE INDEX "ChallengeCategory.id_unique" ON "ChallengeCategory"("id");
-- AddForeignKey
ALTER TABLE "UserChallenge" ADD FOREIGN KEY ("challengeId") REFERENCES "Challenge"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "UserChallenge" ADD FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Challenge" ADD FOREIGN KEY ("challengeStateId") REFERENCES "ChallengeState"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Challenge" ADD FOREIGN KEY ("challengeCategoryId") REFERENCES "ChallengeCategory"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ChallengeTag" ADD FOREIGN KEY ("challengeId") REFERENCES "Challenge"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ChallengeNote" ADD FOREIGN KEY ("challengeId") REFERENCES "Challenge"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
-- staging to consumption (Origin)
insert into consumption (client_id,day,prd,kwh)
select
5 as client_id,
(date '22/08/2013'-date '01/01/2010') + (t.id-(select min(id) from staging_origin1))/48+1 as day,
(case (time)
when '12:30:00 AM' then 1 when '01:00:00 AM' then 2 when '01:30:00 AM' then 3 when '02:00:00 AM' then 4
when '02:30:00 AM' then 5 when '03:00:00 AM' then 6 when '03:30:00 AM' then 7 when '04:00:00 AM' then 8
when '04:30:00 AM' then 9 when '05:00:00 AM' then 10 when '05:30:00 AM' then 11 when '06:00:00 AM' then 12
when '06:30:00 AM' then 13 when '07:00:00 AM' then 14 when '07:30:00 AM' then 15 when '08:00:00 AM' then 16
when '08:30:00 AM' then 17 when '09:00:00 AM' then 18 when '09:30:00 AM' then 19 when '10:00:00 AM' then 20
when '10:30:00 AM' then 21 when '11:00:00 AM' then 22 when '11:30:00 AM' then 23 when '12:00:00 PM' then 24
when '12:30:00 PM' then 25 when '01:00:00 PM' then 26 when '01:30:00 PM' then 27 when '02:00:00 PM' then 28
when '02:30:00 PM' then 29 when '03:00:00 PM' then 30 when '03:30:00 PM' then 31 when '04:00:00 PM' then 32
when '04:30:00 PM' then 33 when '05:00:00 PM' then 34 when '05:30:00 PM' then 35 when '06:00:00 PM' then 36
when '06:30:00 PM' then 37 when '07:00:00 PM' then 38 when '07:30:00 PM' then 39 when '08:00:00 PM' then 40
when '08:30:00 PM' then 41 when '09:00:00 PM' then 42 when '09:30:00 PM' then 43 when '10:00:00 PM' then 44
when '10:30:00 PM' then 45 when '11:00:00 PM' then 46 when '11:30:00 PM' then 47 when '12:00:00 AM' then 48
else 999
end) as prd,
kwh::numeric(8,2) as kwh
from
(
select
id,
content,
substring(content,8,2) as date_month,
substring(content,5,2) as date_day,
substring(content,11,11) as time,
substring(content,position('M ' in content)+2,length(content)) as kwh
from staging_origin1
) t;
|
-- 227428 "SOFA Score"
-- 226738 "AgeApacheIIScore"
-- 226749 "ChpApacheIIScore"
-- 226751 "CreatinineApacheIIScore"
-- 226753 "DswfApacheScore"
-- 226755 "GcsApacheIIScore"
-- 87 "Braden Score"
-- 4490 "NAS Score"
-- 5927 "NAS score"
-- 226760 "HCO3Score"
-- 226761 "HematocritApacheIIScore"
-- 226763 "HrApacheIIScore"
-- 226765 "MapApacheIIScore"
-- 226767 "OxygenApacheIIScore"
-- 226768 "PhApacheIIScore"
-- 226771 "PotassiumApacheIIScore"
-- 226773 "RrApacheIIScore"
-- 226775 "SodiumApacheIIScore"
-- 226777 "TempApacheIIScore"
-- 226779 "WbcApacheIIScore"
-- 226980 "AgeScore_ApacheIV"
-- 226982 "AlbuminScore_ApacheIV"
-- 226999 "BiliScore_ApacheIV"
-- 227001 "BunScore_ApacheIV"
-- 227004 "ChronicScore_ApacheIV" |
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50621
Source Host : localhost:3306
Source Database : baseplatform
Target Server Type : MYSQL
Target Server Version : 50621
File Encoding : 65001
Date: 2019-05-08 17:10:50
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for t_sys_dictionary
-- ----------------------------
DROP TABLE IF EXISTS `t_sys_dictionary`;
CREATE TABLE `t_sys_dictionary` (
`ID` varchar(32) NOT NULL COMMENT '主键ID',
`CODE` varchar(100) NOT NULL COMMENT '数据项code',
`NAME` varchar(100) NOT NULL COMMENT '数据项名称',
`ORDER_INDEX` decimal(65,30) NOT NULL COMMENT '数据项顺序',
`STATUS` char(1) NOT NULL COMMENT '状态(0-未启用;已启用)',
`PID` varchar(32) NOT NULL COMMENT '父数据项',
`DESCRIPTION` varchar(200) DEFAULT NULL COMMENT '说明',
`CREATE_TIME` datetime NOT NULL COMMENT '创建时间',
`CREATOR` varchar(32) NOT NULL COMMENT '创建者',
`LAST_UPDATE_TIME` datetime DEFAULT NULL COMMENT '修改时间',
`LAST_UPDATOR` varchar(32) DEFAULT NULL COMMENT '修改者',
`DEL_FLAG` char(1) NOT NULL COMMENT '删除标识(0-未删除;1-已删除)',
`VALUE` text COMMENT '数据项值',
`LEV` decimal(65,30) DEFAULT NULL COMMENT '树形结构层次',
`SUBSIDIARY` varchar(32) DEFAULT NULL COMMENT '所属公司',
PRIMARY KEY (`ID`),
KEY `INDEX_T_SYS_DICTIONARY_PID` (`PID`) USING BTREE,
KEY `UNIQUE_CODE` (`CODE`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用于记录系统的基本数据信息';
|
-- 24/10/2019 - payment_method for orders
ALTER TABLE `orders` ADD `payment_method` varchar(50) NULL AFTER `payment_description`; |
CREATE TABLE IF NOT EXISTS ACCOUNTS(
ID INT AUTO_INCREMENT,
EMAIL_ADDRESS VARCHAR(63) NOT NULL,
HASH_PASSWORD VARCHAR(127) NOT NULL,
FIRST_NAME VARCHAR(31) NOT NULL,
LAST_NAME VARCHAR(31) NOT NULL,
SECURITY_LEVEL INT DEFAULT 0,
IS_ACTIVE ENUM('0', '1') DEFAULT '1',
PRIMARY KEY(ID),
UNIQUE KEY(EMAIL_ADDRESS));
CREATE TABLE IF NOT EXISTS PROJECTS(
ID INT AUTO_INCREMENT,
PROJ_NAME VARCHAR(63) NOT NULL,
IS_ACTIVE ENUM('0', '1') DEFAULT '1',
PRIMARY KEY(ID),
UNIQUE KEY (PROJ_NAME));
CREATE TABLE IF NOT EXISTS ISSUE_CATEGORIES(
ID INT AUTO_INCREMENT,
CAT_NAME VARCHAR(63) NOT NULL,
IS_ACTIVE ENUM('0', '1') DEFAULT '1',
PRIMARY KEY(ID),
UNIQUE KEY (CAT_NAME));
CREATE TABLE IF NOT EXISTS TIME_CATEGORIES(
ID INT AUTO_INCREMENT,
CAT_NAME VARCHAR(15) NOT NULL,
IS_ACTIVE ENUM('0', '1') DEFAULT '1',
PRIMARY KEY(ID),
UNIQUE KEY(CAT_NAME));
CREATE TABLE IF NOT EXISTS PRIORITIES(
ID INT AUTO_INCREMENT,
PRI_NAME VARCHAR(63) NOT NULL,
IS_ACTIVE ENUM('0', '1') DEFAULT '1',
PRIMARY KEY(ID),
UNIQUE KEY(PRI_NAME));
CREATE TABLE IF NOT EXISTS STATUSES(
ID INT AUTO_INCREMENT,
STAT_NAME VARCHAR(63) NOT NULL,
IS_ACTIVE ENUM('0', '1') DEFAULT '1',
PRIMARY KEY(ID),
UNIQUE KEY(STAT_NAME));
CREATE TABLE IF NOT EXISTS ACCOUNT_PROJECT_DOMAINS(
ID INT AUTO_INCREMENT,
ACCOUNT_ID INT,
PROJECT_ID INT,
PRIMARY KEY(ID),
FOREIGN KEY(ACCOUNT_ID)
REFERENCES ACCOUNTS(ID),
FOREIGN KEY(PROJECT_ID)
REFERENCES PROJECTS(ID));
CREATE TABLE IF NOT EXISTS PROJECT_EMAILS(
ID INT AUTO_INCREMENT,
ACCOUNT_ID INT,
PROJECT_ID INT,
PRIMARY KEY(ID),
FOREIGN KEY(ACCOUNT_ID)
REFERENCES ACCOUNTS(ID),
FOREIGN KEY(PROJECT_ID)
REFERENCES PROJECTS(ID));
CREATE TABLE IF NOT EXISTS PROJECT_TIME_CATEGORIES(
ID INT AUTO_INCREMENT,
PROJECT_ID INT,
CATEGORY_ID INT,
PRIMARY KEY(ID),
FOREIGN KEY(PROJECT_ID)
REFERENCES PROJECTS(ID),
FOREIGN KEY(CATEGORY_ID)
REFERENCES TIME_CATEGORIES(ID));
CREATE TABLE IF NOT EXISTS ACCOUNT_SAVED_REPORTS(
ID INT AUTO_INCREMENT,
ACCOUNT_ID INT,
REPORT_QUERY VARCHAR(127) NOT NULL,
IS_SHARED ENUM('0', '1') DEFAULT '0',
PRIMARY KEY(ID),
FOREIGN KEY(ACCOUNT_ID)
REFERENCES ACCOUNTS(ID));
CREATE TABLE IF NOT EXISTS ACCOUNT_SAVED_QUERIES(
ID INT AUTO_INCREMENT,
ACCOUNT_ID INT,
SAVED_QUERY VARCHAR(127) NOT NULL,
PRIMARY KEY(ID),
FOREIGN KEY(ACCOUNT_ID)
REFERENCES ACCOUNTS(ID));
CREATE TABLE IF NOT EXISTS ISSUES(
ID INT AUTO_INCREMENT,
TITLE VARCHAR(63) NOT NULL,
PROJECT_ID INT,
CATEGORY_ID INT,
ASSIGNED_ID INT,
CREATED_ID INT,
STATUS_ID INT,
PRIORITY_ID INT,
IS_LEGACY ENUM('0', '1') DEFAULT '0',
PRIMARY KEY(ID),
FOREIGN KEY (PROJECT_ID)
REFERENCES PROJECTS(ID),
FOREIGN KEY(CATEGORY_ID)
REFERENCES ISSUE_CATEGORIES(ID),
FOREIGN KEY(ASSIGNED_ID)
REFERENCES ACCOUNTS(ID),
FOREIGN KEY(CREATED_ID)
REFERENCES ACCOUNTS(ID),
FOREIGN KEY(STATUS_ID)
REFERENCES STATUSES(ID),
FOREIGN KEY(PRIORITY_ID)
REFERENCES PRIORITIES(ID));
CREATE TABLE IF NOT EXISTS ISSUE_COMMENTS(
ID INT AUTO_INCREMENT,
ISSUE_ID INT,
ACCOUNT_ID INT,
COMM_TIME DATETIME,
COMM_STRING VARCHAR(2500),
IS_PRIVATE ENUM('0', '1') DEFAULT '0',
PRIMARY KEY(ID),
FOREIGN KEY(ISSUE_ID)
REFERENCES ISSUES(ID),
FOREIGN KEY(ACCOUNT_ID)
REFERENCES ACCOUNTS(ID));
CREATE TABLE IF NOT EXISTS ISSUE_FILES(
ID INT AUTO_INCREMENT,
ISSUE_ID INT,
ACCOUNT_ID INT,
FILE_TIME DATETIME,
FILE_NAME VARCHAR(127),
PRIMARY KEY(ID),
FOREIGN KEY(ISSUE_ID)
REFERENCES ISSUES(ID),
FOREIGN KEY(ACCOUNT_ID)
REFERENCES ACCOUNTS(ID));
CREATE TABLE IF NOT EXISTS ISSUE_NOTIFICATION(
ID INT AUTO_INCREMENT,
ISSUE_ID INT,
ACCOUNT_ID INT,
PRIMARY KEY(ID),
FOREIGN KEY(ISSUE_ID)
REFERENCES ISSUES(ID),
FOREIGN KEY(ACCOUNT_ID)
REFERENCES ACCOUNTS(ID));
CREATE TABLE IF NOT EXISTS TIME_TRACKING(
ID INT AUTO_INCREMENT,
ACCOUNT_ID INT,
ISSUE_ID INT,
PROJECT_ID INT,
WORK_DATE DATE NOT NULL,
HOURS INT NOT NULL,
PRIMARY KEY(ID),
FOREIGN KEY(ACCOUNT_ID)
REFERENCES ACCOUNTS(ID),
FOREIGN KEY(ISSUE_ID)
REFERENCES ISSUES(ID),
FOREIGN KEY(PROJECT_ID)
REFERENCES PROJECTS(ID)); |
/*20180104*/
/*USE ODS;
DROP TABLE IF EXISTS ODS_HC_CLIENTES;
TRUNCATE TABLE ODS_HC_CLIENTES;
CREATE TABLE ODS_HC_CLIENTES
(ID_CLIENTE INT NOT NULL PRIMARY KEY
, NOMBRE_CLIENTE VARCHAR(512)
, APELLIDOS_CLIENTE VARCHAR(512)
, NUMDOC_CLIENTE VARCHAR(24)
, ID_SEXO INT(10) UNSIGNED
, ID_DIRECCION_CLIENTE INT
, TELEFONO_CLIENTE BIGINT
, EMAIL VARCHAR(512)
, FC_NACIMIENTO DATE
, ID_PROFESION INT
, ID_COMPANYA INT
, FC_INSERT DATETIME
, FC_MODIFICACION DATETIME);
*/
/*
USE ODS;
DROP TABLE IF EXISTS ODS_DM_SEXOS;
CREATE TABLE ODS_DM_SEXOS
(ID_SEXO INT UNSIGNED AUTO_INCREMENT PRIMARY KEY
, DE_SEXO VARCHAR(64)
, FC_INSERT DATETIME
, FC_MODIFICACION DATETIME);
*/
/*USE ODS;
DROP TABLE IF EXISTS ODS_DM_PROFESIONES;
CREATE TABLE ODS_DM_PROFESIONES
(ID_PROFESION INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY
, DE_PROFESION VARCHAR(512)
, FC_INSERT DATETIME
, FC_MODIFICACION DATETIME);*/
/*USE ODS;
DROP TABLE IF EXISTS ODS_DM_COMPANYAS;
CREATE TABLE ODS_DM_COMPANYAS
(ID_COMPANYA INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY
, DE_COMPANYA VARCHAR(512)
, FC_INSERT DATETIME
, FC_MODIFICACION DATETIME);
*/
/*USE ODS;
DROP TABLE IF EXISTS ODS_HC_DIRECCIONES;
CREATE TABLE ODS_HC_DIRECCIONES
(ID_DIRECCION INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY
, DE_DIRECCION VARCHAR(512)
, DE_CP INT
, ID_CIUDAD_ESTADO INT
, FC_INSERT DATETIME
, FC_MODIFICACION DATETIME);*/
/*USE ODS;
SET FOREIGN_KEY_CHECKS=0;
SET FOREIGN_KEY_CHECKS=1;
TRUNCATE TABLE ODS_DM_CIUDADES_ESTADOS;
DROP TABLE IF EXISTS ODS_DM_CIUDADES_ESTADOS;
CREATE TABLE ODS_DM_CIUDADES_ESTADOS
(ID_CIUDAD_ESTADO INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY
, DE_CIUDAD VARCHAR(512)
, DE_ESTADO VARCHAR(512)
, ID_PAIS INT
, FC_INSERT DATETIME
, FC_MODIFICACION DATETIME);*/
/*
USE ODS;
SET FOREIGN_KEY_CHECKS=1;
TRUNCATE ODS_DM_PAISES;
DROP TABLE IF EXISTS ODS_DM_PAISES;
CREATE TABLE ODS_DM_PAISES
(ID_PAIS INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY
, DE_PAIS VARCHAR(512)
, FC_INSERT DATETIME
, FC_MODIFICACION DATETIME);*/
/*CREAMOS LAS FK DEL MODELO DE CLIENTES*/
/*
USE ODS;
ALTER TABLE ODS.ODS_HC_CLIENTES ADD INDEX fk_cli_sexo_idx (ID_SEXO ASC);
ALTER TABLE ODS.ODS_HC_CLIENTES ADD CONSTRAINT fk_cli_sexo FOREIGN KEY (ID_SEXO)
REFERENCES ODS.ODS_DM_SEXOS (ID_SEXO);
#ALTER TABLE ODS.ODS_HC_CLIENTES MODIFY COLUMN ID_PROFESION INT(10) UNSIGNED;
ALTER TABLE ODS.ODS_HC_CLIENTES ADD INDEX fk_cli_prof_idx (ID_PROFESION ASC);
ALTER TABLE ODS.ODS_HC_CLIENTES ADD CONSTRAINT fk_cli_prof_idx FOREIGN KEY (ID_PROFESION)
REFERENCES ODS.ODS_DM_PROFESIONES (ID_PROFESION);
#ALTER TABLE ODS.ODS_HC_CLIENTES MODIFY COLUMN ID_COMPANYA INT(10) UNSIGNED;
ALTER TABLE ODS.ODS_HC_CLIENTES ADD INDEX fk_cli_comp_idx (ID_COMPANYA ASC);
ALTER TABLE ODS.ODS_HC_CLIENTES ADD CONSTRAINT fk_cli_comp FOREIGN KEY (ID_COMPANYA)
REFERENCES ODS.ODS_DM_COMPANYAS (ID_COMPANYA);
#ALTER TABLE ODS.ODS_HC_CLIENTES MODIFY COLUMN ID_DIRECCION_CLIENTE INT(10) UNSIGNED;
ALTER TABLE ODS.ODS_HC_CLIENTES ADD INDEX fk_cli_dir_idx (ID_DIRECCION_CLIENTE ASC);
ALTER TABLE ODS.ODS_HC_CLIENTES ADD CONSTRAINT fk_cli_dir FOREIGN KEY (ID_DIRECCION_CLIENTE)
REFERENCES ODS.ODS_HC_DIRECCIONES (ID_DIRECCION);
#ALTER TABLE ODS.ODS_DM_CIUDADES_ESTADOS MODIFY COLUMN ID_PAIS INT(10) UNSIGNED;
ALTER TABLE ODS.ODS_DM_CIUDADES_ESTADOS ADD INDEX fk_ciu_pai_idx (ID_PAIS ASC);
ALTER TABLE ODS.ODS_DM_CIUDADES_ESTADOS ADD CONSTRAINT fk_ciu_pai FOREIGN KEY (ID_PAIS)
REFERENCES ODS.ODS_DM_PAISES (ID_PAIS);
#ALTER TABLE ODS.ODS_HC_DIRECCIONES MODIFY COLUMN ID_CIUDAD_ESTADO INT(10) UNSIGNED;
ALTER TABLE ODS.ODS_HC_DIRECCIONES ADD INDEX fk_dir_ciu_idx (ID_CIUDAD_ESTADO ASC);
ALTER TABLE ODS.ODS_HC_DIRECCIONES ADD CONSTRAINT fk_dir_ciu FOREIGN KEY (ID_CIUDAD_ESTADO)
REFERENCES ODS.ODS_DM_CIUDADES_ESTADOS(ID_CIUDAD_ESTADO);
*/
/*POBLADO DE DATOS*/
/*
USE ODS;
INSERT INTO ODS_DM_SEXOS VALUES (1,'MALE',now(),now());
INSERT INTO ODS_DM_SEXOS VALUES (2,'FEMALE',now(),now());
INSERT INTO ODS_DM_SEXOS VALUES (99,'DESCONOCIDO',now(),now());
INSERT INTO ODS_DM_SEXOS VALUES (98,'NO APLICA',now(),now());
COMMIT;
ANALYZE TABLE ODS_DM_SEXOS;
*/
/*
INSERT INTO ODS_DM_PROFESIONES(DE_PROFESION,FC_INSERT,FC_MODIFICACION)
SELECT DISTINCT UPPER(TRIM(PROFESION)) PROFESION, NOW(),NOW()
FROM STAGE.STG_CLIENTES_CRM
WHERE TRIM(PROFESION)<>'';
COMMIT;
INSERT INTO ODS_DM_PROFESIONES VALUES (9998,'NO APLICA', NOW(),NOW());
INSERT INTO ODS_DM_PROFESIONES VALUES (9999,'DESCONOCIDO', NOW(),NOW());
ANALYZE TABLE ODS_DM_PROFESIONES;
INSERT INTO ODS_DM_COMPANYAS (DE_COMPANYA, FC_INSERT, FC_MODIFICACION)
SELECT distinct UPPER(TRIM(COMPANY)) DE_COMPANYA, NOW(), now()
FROM STAGE.STG_CLIENTES_CRM
WHERE length(TRIM(COMPANY))<>0;
INSERT INTO ODS_DM_COMPANYAS VALUES (99998,'NO APLICA', NOW(),NOW());
INSERT INTO ODS_DM_COMPANYAS VALUES (99999,'DESCONOCIDO', NOW(),NOW());
ANALYZE TABLE ODS_DM_COMPANYAS;
*/
/*
INSERT INTO ODS_DM_PAISES (DE_PAIS, FC_INSERT, FC_MODIFICACION)
SELECT distinct UPPER(TRIM(COUNTRY)) PAIS, NOW(), NOW()
FROM STAGE.STG_CLIENTES_CRM
WHERE TRIM(COUNTRY)<>'';
INSERT INTO ODS_DM_PAISES VALUES (98,'NO APLICA', NOW(),NOW());
INSERT INTO ODS_DM_PAISES VALUES (99,'DESCONOCIDO', NOW(),NOW());
ANALYZE TABLE ODS_DM_PAISES;
INSERT INTO ODS_DM_CIUDADES_ESTADOS (DE_CIUDAD, DE_ESTADO, ID_PAIS, FC_INSERT, FC_MODIFICACION)
select distinct case when TRIM(CITY)<>'' THEN UPPER(TRIM(CITY)) ELSE 'DESCONOCIDO' END CIUDAD
, CASE WHEN TRIM(STATE)<>'' THEN UPPER(TRIM(STATE)) ELSE 'DESCONOCIDO'END ESTADO, PAI.ID_PAIS, NOW(), NOW()
FROM STAGE.STG_CLIENTES_CRM CLI
INNER JOIN ODS.ODS_DM_PAISES PAI ON CASE WHEN length(TRIM(CLI.COUNTRY))<>0 THEN CLI.COUNTRY ELSE 'DESCONOCIDO' END=PAI.DE_PAIS
WHERE TRIM(CITY)<>'' OR TRIM(STATE)<>'';
INSERT INTO ODS_DM_CIUDADES_ESTADOS VALUES (9998,'NO APLICA', 99, 99, NOW(),NOW());
INSERT INTO ODS_DM_CIUDADES_ESTADOS VALUES (9999,'DESCONOCIDO', 98, 98, NOW(),NOW());
ANALYZE TABLE ODS_DM_CIUDADES_ESTADOS;
INSERT INTO ODS_HC_DIRECCIONES (DE_DIRECCION, DE_CP, ID_CIUDAD_ESTADO, FC_INSERT, FC_MODIFICACION)
select distinct UPPER(TRIM(ADDRESS)) DIRECCION
, CASE WHEN length(TRIM(CLI.POSTAL_CODE))<>0 THEN TRIM(CLI.POSTAL_CODE) ELSE 99999 END CP,CIU.ID_CIUDAD_ESTADO, NOW(), NOW()
FROM STAGE.STG_CLIENTES_CRM CLI
INNER JOIN ODS.ODS_DM_PAISES PAI ON CASE WHEN length(TRIM(CLI.COUNTRY))<>0 THEN CLI.COUNTRY ELSE 'DESCONOCIDO' END=PAI.DE_PAIS
INNER JOIN ODS.ODS_DM_CIUDADES_ESTADOS CIU ON CASE WHEN LENGTH(TRIM(CLI.CITY))<>0 THEN CLI.CITY ELSE 'DESCONOCIDO' END=CIU.DE_CIUDAD
AND CASE WHEN LENGTH(TRIM(CLI.STATE))<>0 THEN CLI.STATE ELSE 'DESCONOCIDO' END=CIU.DE_ESTADO
WHERE LENGTH(TRIM(ADDRESS))<>0;
ANALYZE TABLE ODS_HC_DIRECCIONES;
SET FOREIGN_KEY_CHECKS=0;
INSERT INTO ODS_HC_DIRECCIONES VALUES (999998,'NO APLICA', 99998, 998, NOW(),NOW());
INSERT INTO ODS_HC_DIRECCIONES VALUES (999999,'DESCONOCIDO',99999, 999,NOW(),NOW());
SET FOREIGN_KEY_CHECKS=1;
ANALYZE TABLE ODS_HC_DIRECCIONES;
USE ODS;
DROP TABLE IF EXISTS TMP_DIRECCIONES_CLIENTES;
CREATE TABLE TMP_DIRECCIONES_CLIENTES AS
SELECT DIR.ID_DIRECCION
, DIR.DE_DIRECCION
, DIR.DE_CP
, CIU.DE_CIUDAD
, CIU.DE_ESTADO
, PAI.DE_PAIS
FROM ODS.ODS_HC_DIRECCIONES DIR
INNER JOIN ODS.ODS_DM_CIUDADES_ESTADOS CIU ON DIR.ID_CIUDAD_ESTADO=CIU.ID_CIUDAD_ESTADO
INNER JOIN ODS_DM_PAISES PAI ON CIU.ID_PAIS=PAI.ID_PAIS;
ANALYZE TABLE TMP_DIRECCIONES_CLIENTES;
DROP TABLE IF EXISTS TMP_DIRECCIONES_CLIENTES2;
CREATE TABLE TMP_DIRECCIONES_CLIENTES2 AS
SELECT CLIENTES.CUSTOMER_ID ID_CLIENTE
, DIR.ID_DIRECCION
FROM STAGE.STG_CLIENTES_CRM CLIENTES
INNER JOIN ODS.TMP_DIRECCIONES_CLIENTES DIR ON CASE WHEN TRIM(ADDRESS)<>'' THEN UPPER(TRIM(CLIENTES.ADDRESS)) ELSE 'DESCONOCIDO' END=DIR.DE_DIRECCION
AND CASE WHEN TRIM(CLIENTES.POSTAL_CODE)<>'' THEN TRIM(CLIENTES.POSTAL_CODE) ELSE 99999 END=DIR.DE_CP
AND CASE WHEN TRIM(CLIENTES.CITY)<>'' THEN CLIENTES.CITY ELSE 'DESCONOCIDO' END=DIR.DE_CIUDAD
AND CASE WHEN TRIM(CLIENTES.STATE)<>'' THEN CLIENTES.STATE ELSE 'DESCONOCIDO' END=DIR.DE_ESTADO
AND CASE WHEN TRIM(CLIENTES.COUNTRY)<>'' THEN CLIENTES.COUNTRY ELSE 'DESCONOCIDO' END=DIR.DE_PAIS;
ANALYZE TABLE TMP_DIRECCIONES_CLIENTES2;
*/
/*
USE ODS;
INSERT INTO ODS_HC_CLIENTES
select CUSTOMER_ID ID_CLIENTE
, CASE WHEN length(TRIM(FIRST_NAME))<>0 THEN TRIM(UPPER(FIRST_NAME)) ELSE 'DESCONOCIDO' END NOMBRE_CLIENTE
, CASE WHEN length(TRIM(LAST_NAME))<>0 THEN TRIM(UPPER(LAST_NAME)) ELSE 'DESCONOCIDO' END APELLIDOS_CLIENTE
, CASE WHEN length(TRIM(IDENTIFIED_DOC))<>0 THEN TRIM(UPPER(IDENTIFIED_DOC)) ELSE '99-999-9999' END NUMDOC_CLIENTE
, ID_SEXO
, CASE WHEN length(TRIM(DIR.ID_DIRECCION))<>0 THEN DIR.ID_DIRECCION ELSE 999999 END ID_DIRECCION
, CASE WHEN length(TRIM(PHONE))<>0 THEN REPLACE(PHONE,'-','') ELSE 999999999 END TELEFONO_CLIENTE
, CASE WHEN length(TRIM(EMAIL))<>0 THEN TRIM(UPPER(EMAIL)) ELSE 'DESCONOCIDO' END EMAIL
, CASE WHEN length(TRIM(BIRTHDAY))<>0 THEN str_to_date(BIRTHDAY, '%d/%m/%Y') ELSE str_to_date('31/12/9999', '%d/%m/%Y') END FC_NACIMIENTO
, PROF.ID_PROFESION
, COMP.ID_COMPANYA
, NOW()
, NOW()
from STAGE.STG_CLIENTES_CRM CLIENTES
INNER JOIN ODS.ODS_DM_SEXOS SEXO ON CASE WHEN LENGTH(TRIM(GENDER))<>0 THEN UPPER(TRIM(CLIENTES.GENDER)) ELSE 'DESCONOCIDO' END=SEXO.DE_SEXO
INNER JOIN ODS.ODS_DM_PROFESIONES PROF ON CASE WHEN LENGTH(TRIM(PROFESION))<>0 THEN UPPER(TRIM(CLIENTES.PROFESION)) ELSE 'NO APLICA' END=PROF.DE_PROFESION
INNER JOIN ODS.ODS_DM_COMPANYAS COMP ON CASE WHEN LENGTH(TRIM(COMPANY))<>0 THEN UPPER(TRIM(CLIENTES.COMPANY)) ELSE 'DESCONOCIDO' END=COMP.DE_COMPANYA
LEFT OUTER JOIN ODS.TMP_DIRECCIONES_CLIENTES2 DIR ON DIR.ID_CLIENTE=CLIENTES.CUSTOMER_ID;
ANALYZE TABLE ODS_HC_CLIENTES;
*/
|
ALTER TABLE authors ADD booleanColumn BIT(1) NULL
ALTER TABLE authors ALTER booleanColumn SET DEFAULT 1 |
SELECT DATE_TRUNC('day',membership_started_at_utc) AS day, id AS user_id, membership_type, membership_state
FROM /*mode.*/organization_usage.users u
|
CREATE DATABASE project1q9_db;
SHOW DATABASES;
USE project1q9_db;
CREATE TABLE P1Q9T1 (
domain_code STRING,
page_title STRING,
count_views INT,
total_response_size INT)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ' ';
LOAD DATA LOCAL INPATH '/home/cjen/pageviews_2101/pageviews-20210120.tsv' INTO TABLE P1Q9T1;
SELECT * FROM P1Q9T1;
INSERT OVERWRITE DIRECTORY '/user/hive/p1q9t1'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
SELECT page_title, SUM(count_views) AS total_count_views FROM P1Q9T1
GROUP BY page_title
ORDER BY total_count_views DESC
LIMIT 100;
INSERT OVERWRITE DIRECTORY '/user/hive/p1q9t2'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
SELECT page_title, SUM(count_views) AS total_count_views FROM P1Q9T1
WHERE domain_code LIKE 'en%'
GROUP BY page_title
ORDER BY total_count_views DESC
LIMIT 100; |
-- phpMyAdmin SQL Dump
-- version 4.9.7
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Oct 04, 2021 at 08:58 AM
-- Server version: 5.7.32
-- PHP Version: 7.4.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Database: `todo_node`
--
-- --------------------------------------------------------
--
-- Table structure for table `buckets`
--
CREATE TABLE `buckets` (
`id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`createdAt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `buckets`
--
INSERT INTO `buckets` (`id`, `name`, `createdAt`, `updatedAt`) VALUES
(11, 'bucket A', '2021-10-04 00:11:08', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `tasks`
--
CREATE TABLE `tasks` (
`id` bigint(20) NOT NULL,
`bucket_id` int(11) DEFAULT NULL,
`user_id` bigint(20) NOT NULL,
`title` varchar(512) NOT NULL,
`description` varchar(2048) DEFAULT NULL,
`due_on` datetime DEFAULT NULL,
`status` enum('complete','incomplete') NOT NULL DEFAULT 'incomplete',
`priority` enum('Low','Medium','High') NOT NULL DEFAULT 'Low',
`createdAt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `tasks`
--
INSERT INTO `tasks` (`id`, `bucket_id`, `user_id`, `title`, `description`, `due_on`, `status`, `priority`, `createdAt`, `updatedAt`) VALUES
(1, 11, 5, 'title', 'The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from \"de Finib', '2021-10-04 03:54:00', 'incomplete', 'Low', '2021-10-04 00:51:30', NULL),
(3, 11, 5, 'title', 'erator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem ', '2021-10-04 15:20:00', 'incomplete', 'High', '2021-10-04 01:25:23', NULL),
(4, 11, 5, 'Title 2', 'qIt was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using \'Content here, content here\', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for \'lorem ipsum\' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).', '2021-10-04 15:28:00', 'complete', 'Medium', '2021-10-04 13:27:01', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(10) UNSIGNED NOT NULL,
`first_name` varchar(30) DEFAULT NULL,
`last_name` varchar(30) DEFAULT NULL,
`gender` varchar(10) DEFAULT NULL,
`email_address` varchar(50) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `first_name`, `last_name`, `gender`, `email_address`, `password`, `created_at`) VALUES
(5, 'Azhar', 'sayyed', 'on', 'asayyed910@gmail.com', '123', '2021-10-03 00:12:52');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `buckets`
--
ALTER TABLE `buckets`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `tasks`
--
ALTER TABLE `tasks`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `buckets`
--
ALTER TABLE `buckets`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT for table `tasks`
--
ALTER TABLE `tasks`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
|
create table users (
id int(32) unsigned auto_increment primary key,
name varchar(64) not null,
`host` varchar(64) not null
);
create table files (
id int(32) unsigned auto_increment primary key,
folder_id int(32) unsigned not null,
foreign key(folder_id) references folders(id)
);
create table folders (
id int(32) unsigned auto_increment primary key,
name varchar(64) not null,
parent_folder_id int(32) unsigned null,
foreign key(parent_folder_id) references folders(id)
);
create table blobs (
id int(32) unsigned auto_increment primary key,
`blob` longblob not null,
mtime timestamp not null,
file_id int(32) unsigned not null,
user_id int(32) unsigned not null,
foreign key(file_id) references files(id),
foreign key(user_id) references users(id)
);
create table downloads (
blob_id int(32) unsigned not null,
user_id int(32) unsigned not null,
`time` timestamp not null,
foreign key(blob_id) references blobs(id),
foreign key(user_id) references users(id)
);
create table tags (
id int(32) unsigned auto_increment primary key,
tag varchar(64) not null
);
create table file_tags (
file_id int(32) unsigned not null,
tag_id int(32) unsigned not null,
foreign key(file_id) references files(id),
foreign key(tag_id) references tags(id)
);
create table folder_tags (
folder_id int(32) unsigned not null,
tag_id int(32) unsigned not null,
foreign key(folder_id) references folders(id),
foreign key(tag_id) references tags(id)
);
|
insert into levels (level, turnover, cashback_percentage, deposit_bonus_percentage, credit_dices, money_credit_rate, bonus_credit_rate, status, created_by, created_date)
values
(1, 0, 0, 0, 0, 0, 0, 'ACTIVE', 1, current_timestamp),
(2, 30000, 0, 0, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(3, 60000, 0, 0, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(4, 90000, 0, 0, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(5, 120000, 0, 0, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(6, 150000, 0, 0, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(7, 180000, 0, 0, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(8, 210000, 0, 0, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(9, 240000, 0, 0, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(10, 270000, 0.25, 10, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(11, 370000, 0.25, 10, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(12, 470000, 0.25, 10, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(13, 570000, 0.25, 10, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(14, 670000, 0.25, 10, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(15, 770000, 0.25, 10, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(16, 870000, 0.25, 10, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(17, 970000, 0.25, 10, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(18, 1070000, 0.25, 10, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(19, 1170000, 0.25, 10, 1, 1, 3, 'ACTIVE', 1, current_timestamp),
(20, 1270000, 0.3, 20, 2, 1, 3, 'ACTIVE', 1, current_timestamp),
(21, 1570000, 0.3, 20, 2, 1, 3, 'ACTIVE', 1, current_timestamp),
(22, 1870000, 0.3, 20, 2, 1, 3, 'ACTIVE', 1, current_timestamp),
(23, 2170000, 0.3, 20, 2, 1, 3, 'ACTIVE', 1, current_timestamp),
(24, 2470000, 0.3, 20, 2, 1, 3, 'ACTIVE', 1, current_timestamp),
(25, 2770000, 0.3, 20, 2, 1, 3, 'ACTIVE', 1, current_timestamp),
(26, 3070000, 0.3, 20, 2, 1, 3, 'ACTIVE', 1, current_timestamp),
(27, 3370000, 0.3, 20, 2, 1, 3, 'ACTIVE', 1, current_timestamp),
(28, 3670000, 0.3, 20, 2, 1, 3, 'ACTIVE', 1, current_timestamp),
(29, 3970000, 0.3, 20, 2, 1, 3, 'ACTIVE', 1, current_timestamp),
(30, 4270000, 0.35, 30, 2, 3, 9, 'ACTIVE', 1, current_timestamp),
(31, 4970000, 0.35, 30, 2, 3, 9, 'ACTIVE', 1, current_timestamp),
(32, 5670000, 0.35, 30, 2, 3, 9, 'ACTIVE', 1, current_timestamp),
(33, 6370000, 0.35, 30, 2, 3, 9, 'ACTIVE', 1, current_timestamp),
(34, 7070000, 0.35, 30, 2, 3, 9, 'ACTIVE', 1, current_timestamp),
(35, 7770000, 0.35, 30, 2, 3, 9, 'ACTIVE', 1, current_timestamp),
(36, 8470000, 0.35, 30, 2, 3, 9, 'ACTIVE', 1, current_timestamp),
(37, 9170000, 0.35, 30, 2, 3, 9, 'ACTIVE', 1, current_timestamp),
(38, 9870000, 0.35, 30, 2, 3, 9, 'ACTIVE', 1, current_timestamp),
(39, 10570000, 0.35, 30, 2, 3, 9, 'ACTIVE', 1, current_timestamp),
(40, 11270000, 0.4, 40, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(41, 12770000, 0.4, 40, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(42, 14270000, 0.4, 40, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(43, 15770000, 0.4, 40, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(44, 17270000, 0.4, 40, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(45, 18770000, 0.4, 40, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(46, 20270000, 0.4, 40, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(47, 21770000, 0.4, 40, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(48, 23270000, 0.4, 40, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(49, 24770000, 0.4, 40, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(50, 26270000, 0.5, 50, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(51, 28770000, 0.5, 50, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(52, 31270000, 0.5, 50, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(53, 33770000, 0.5, 50, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(54, 36270000, 0.5, 50, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(55, 38770000, 0.5, 50, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(56, 41270000, 0.5, 50, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(57, 43770000, 0.5, 50, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(58, 46270000, 0.5, 50, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(59, 48770000, 0.5, 50, 3, 3, 9, 'ACTIVE', 1, current_timestamp),
(60, 51270000, 0.6, 60, 3, 9, 27, 'ACTIVE', 1, current_timestamp),
(61, 55270000, 0.6, 60, 3, 9, 27, 'ACTIVE', 1, current_timestamp),
(62, 59270000, 0.6, 60, 3, 9, 27, 'ACTIVE', 1, current_timestamp),
(63, 63270000, 0.6, 60, 3, 9, 27, 'ACTIVE', 1, current_timestamp),
(64, 67270000, 0.6, 60, 3, 9, 27, 'ACTIVE', 1, current_timestamp),
(65, 71270000, 0.6, 60, 3, 9, 27, 'ACTIVE', 1, current_timestamp),
(66, 75270000, 0.6, 60, 3, 9, 27, 'ACTIVE', 1, current_timestamp),
(67, 79270000, 0.6, 60, 3, 9, 27, 'ACTIVE', 1, current_timestamp),
(68, 83270000, 0.6, 60, 3, 9, 27, 'ACTIVE', 1, current_timestamp),
(69, 87270000, 0.6, 60, 3, 9, 27, 'ACTIVE', 1, current_timestamp),
(70, 91270000, 0.7, 70, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(71, 97270000, 0.7, 70, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(72, 103270000, 0.7, 70, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(73, 109270000, 0.7, 70, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(74, 115270000, 0.7, 70, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(75, 121270000, 0.7, 70, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(76, 127270000, 0.7, 70, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(77, 133270000, 0.7, 70, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(78, 139270000, 0.7, 70, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(79, 145270000, 0.7, 70, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(80, 151270000, 0.8, 80, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(81, 158770000, 0.8, 80, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(82, 166270000, 0.8, 80, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(83, 173770000, 0.8, 80, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(84, 181270000, 0.8, 80, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(85, 188770000, 0.8, 80, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(86, 196270000, 0.8, 80, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(87, 203770000, 0.8, 80, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(88, 211270000, 0.8, 80, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(89, 218770000, 0.8, 80, 4, 9, 27, 'ACTIVE', 1, current_timestamp),
(90, 226270000, 0.9, 90, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(91, 236270000, 0.9, 90, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(92, 246270000, 0.9, 90, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(93, 256270000, 0.9, 90, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(94, 266270000, 0.9, 90, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(95, 276270000, 0.9, 90, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(96, 286270000, 0.9, 90, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(97, 296270000, 0.9, 90, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(98, 306270000, 0.9, 90, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(99, 316270000, 0.9, 90, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(100, 326270000, 1, 100, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(101, 341270000, 1, 100, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(102, 356270000, 1, 100, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(103, 371270000, 1, 100, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(104, 386270000, 1, 100, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(105, 401270000, 1, 100, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(106, 416270000, 1, 100, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(107, 431270000, 1, 100, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(108, 446270000, 1, 100, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(109, 461270000, 1, 100, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(110, 476270000, 1.25, 125, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(111, 501270000, 1.25, 125, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(112, 526270000, 1.25, 125, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(113, 551270000, 1.25, 125, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(114, 576270000, 1.25, 125, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(115, 601270000, 1.25, 125, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(116, 626270000, 1.25, 125, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(117, 651270000, 1.25, 125, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(118, 676270000, 1.25, 125, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(119, 701270000, 1.25, 125, 4, 20, 60, 'ACTIVE', 1, current_timestamp),
(120, 726270000, 1.25, 125, 4, 20, 60, 'ACTIVE', 1, current_timestamp);
|
-- Initialize the database.
-- Drop any existing data and create empty tables.
DROP TABLE IF EXISTS user;
DROP TABLE IF EXISTS invitation;
CREATE TABLE user(
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
);
CREATE TABLE invitation (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
code TEXT UNIQUE NOT NULL,
shareinfo TEXT NOT NULL
);
|
DROP TABLE online_statistics;
|
-- MySQL Script generated by MySQL Workbench
-- Mon May 28 14:58:32 2018
-- 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 bd_unicorn
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema bd_unicorn
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `bd_unicorn` DEFAULT CHARACTER SET utf8 ;
USE `bd_unicorn` ;
-- -----------------------------------------------------
-- Table `bd_unicorn`.`aviao`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `bd_unicorn`.`aviao` (
`id_aviao` INT NOT NULL,
`modelo` VARCHAR(100) NOT NULL,
`ocupacao` INT NOT NULL,
`velocidade` DOUBLE NOT NULL,
`gasto` DOUBLE NOT NULL,
PRIMARY KEY (`id_aviao`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `bd_unicorn`.`aeroporto`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `bd_unicorn`.`aeroporto` (
`id_aeroporto` INT NOT NULL,
`nome` VARCHAR(100) NOT NULL,
`cidade` VARCHAR(100) NOT NULL,
`estado` VARCHAR(100) NOT NULL,
`pais` VARCHAR(100) NOT NULL,
`qtd_avioes` INT NOT NULL,
`id_aviao` INT NOT NULL,
PRIMARY KEY (`id_aeroporto`),
INDEX `fk_aeroporto_aviao_idx` (`id_aviao` ASC),
CONSTRAINT `fk_aeroporto_aviao`
FOREIGN KEY (`id_aviao`)
REFERENCES `bd_unicorn`.`aviao` (`id_aviao`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `bd_unicorn`.`voo`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `bd_unicorn`.`voo` (
`id_voo` INT NOT NULL,
`data_saida` DATE NOT NULL,
`hora_saida` TIME NOT NULL,
`duracao` TIME NOT NULL,
`origem` INT NOT NULL,
`destino` INT NOT NULL,
PRIMARY KEY (`id_voo`),
INDEX `fk_voo_aeroporto1_idx` (`origem` ASC),
INDEX `fk_voo_aeroporto2_idx` (`destino` ASC),
CONSTRAINT `fk_voo_aeroporto1`
FOREIGN KEY (`origem`)
REFERENCES `bd_unicorn`.`aeroporto` (`id_aeroporto`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_voo_aeroporto2`
FOREIGN KEY (`destino`)
REFERENCES `bd_unicorn`.`aeroporto` (`id_aeroporto`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `bd_unicorn`.`passaporte`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `bd_unicorn`.`passaporte` (
`id_passaporte` VARCHAR(8) NOT NULL,
`pais_emissor` VARCHAR(3) NOT NULL,
`sobrenome` VARCHAR(100) NOT NULL,
`nome` VARCHAR(100) NOT NULL,
`nascimento` VARCHAR(100) NOT NULL,
`identidade` VARCHAR(11) NOT NULL,
`sexo` CHAR NOT NULL,
`pai` VARCHAR(100) NOT NULL,
`mae` VARCHAR(100) NOT NULL,
`data_expedicao` DATE NOT NULL,
`valido_ate` DATE NOT NULL,
`autoridade` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id_passaporte`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `bd_unicorn`.`passageiro`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `bd_unicorn`.`passageiro` (
`cpf_passageiro` INT NOT NULL,
`nome` VARCHAR(100) NOT NULL,
`sobrenome` VARCHAR(100) NOT NULL,
`nascimento` DATE NOT NULL,
`sexo` CHAR(1) NOT NULL,
`rg` INT NOT NULL,
`nacionalidade` VARCHAR(100) NOT NULL,
`id_passaporte` VARCHAR(8) NULL,
PRIMARY KEY (`cpf_passageiro`),
INDEX `fk_passageiro_passaporte1_idx` (`id_passaporte` ASC),
CONSTRAINT `fk_passageiro_passaporte1`
FOREIGN KEY (`id_passaporte`)
REFERENCES `bd_unicorn`.`passaporte` (`id_passaporte`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `bd_unicorn`.`passagem`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `bd_unicorn`.`passagem` (
`id_passagem` INT NOT NULL,
`valor` DOUBLE NOT NULL,
`id_voo` INT NOT NULL,
`cpf_passageiro` INT NOT NULL,
PRIMARY KEY (`id_passagem`),
INDEX `fk_passagem_voo1_idx` (`id_voo` ASC),
INDEX `fk_passagem_passageiro1_idx` (`cpf_passageiro` ASC),
CONSTRAINT `fk_passagem_voo1`
FOREIGN KEY (`id_voo`)
REFERENCES `bd_unicorn`.`voo` (`id_voo`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_passagem_passageiro1`
FOREIGN KEY (`cpf_passageiro`)
REFERENCES `bd_unicorn`.`passageiro` (`cpf_passageiro`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
|
-- SELECT c.CountryName,
-- c.CountryCode,
-- CASE
-- WHEN c.CurrencyCode = 'EUR'
-- THEN 'Euro'
-- ELSE 'Not Euro'
-- END AS [Currency]
-- FROM Countries AS c
--ORDER BY c.CountryName
SELECT CountryName, CountryCode,
CASE
WHEN CurrencyCode = 'EUR' THEN 'Euro'
ELSE 'Not Euro'
END
AS [Currency]
FROM Countries
ORDER BY CountryName |
SELECT *
FROM numbers
ORDER BY random(); |
select status,* from KFQ_ContractSc order by regdate
--a1
select count(*)as re from KFQ_ContractSc where status=50
--a2
select convert(varchar,convert(money,sum(ContractAmount)),1) as re from KFQ_ContractSc where status=50
--a3
select count(*)as re from KFQ_ContractSc where status=50 and DATEPART(qq, GETDATE()) = DATEPART(qq,RegDate) and DATEPART(yyyy, GETDATE()) = DATEPART(yyyy,RegDate)
--a4
select convert(varchar,convert(money,sum(ContractAmount)),1) as re from KFQ_ContractSc where status=50 and DATEPART(qq, GETDATE()) = DATEPART(qq,RegDate) and DATEPART(yyyy, GETDATE()) = DATEPART(yyyy,RegDate)
--a5
select count(*)as re from KFQ_ContractSc where status=50 and DATEPART(mm, GETDATE()) = DATEPART(mm,RegDate) and DATEPART(yyyy, GETDATE()) = DATEPART(yyyy,RegDate)
--a6
select convert(varchar,convert(money,sum(ContractAmount)),1) as re from KFQ_ContractSc where status=50 and DATEPART(mm, GETDATE()) = DATEPART(mm,RegDate) and DATEPART(yyyy, GETDATE()) = DATEPART(yyyy,RegDate)
select * from KFQ_PAY_PLAN_BILL
--b1
select convert(varchar,convert(money,sum(payingfee)),1) as re from KFQ_PAY_PLAN_BILL where DATEPART(yyyy, GETDATE()) = DATEPART(yyyy,RegDate)
--b2
select convert(varchar,convert(money,sum(payingfee)),1) as re from KFQ_PAY_PLAN_BILL where DATEPART(qq, GETDATE()) = DATEPART(qq,RegDate) and DATEPART(yyyy, GETDATE()) = DATEPART(yyyy,RegDate)
--b3
select convert(varchar,convert(money,sum(payingfee)),1) as re from KFQ_PAY_PLAN_BILL where DATEPART(mm, GETDATE()) = DATEPART(mm,RegDate) and DATEPART(yyyy, GETDATE()) = DATEPART(yyyy,RegDate)
select * from KFQ_PAY_CONTPAY_RECORD
--c1
select convert(varchar,convert(money,sum(apply_money)),1) as re from KFQ_PAY_CONTPAY_RECORD where DATEPART(yyyy, GETDATE()) = DATEPART(yyyy,RegDate)
--c2
select convert(varchar,convert(money,isnull(sum(apply_money),0)),1) as re from KFQ_PAY_CONTPAY_RECORD where DATEPART(qq, GETDATE()) = DATEPART(qq,RegDate) and DATEPART(yyyy, GETDATE()) = DATEPART(yyyy,RegDate)
--c3
select convert(varchar,convert(money,isnull(sum(apply_money),0)),1) as re from KFQ_PAY_CONTPAY_RECORD where DATEPART(mm, GETDATE()) = DATEPART(mm,RegDate) and DATEPART(yyyy, GETDATE()) = DATEPART(yyyy,RegDate)
select * from KFQ_PAY_CHANGE_BILL
--d1
select convert(varchar,convert(money,sum(changeSum)),1) as re from KFQ_PAY_CHANGE_BILL where DATEPART(yyyy, GETDATE()) = DATEPART(yyyy,RegDate)
--d2
select convert(varchar,convert(money,isnull(sum(changeSum),0)),1) as re from KFQ_PAY_CHANGE_BILL where DATEPART(qq, GETDATE()) = DATEPART(qq,RegDate) and DATEPART(yyyy, GETDATE()) = DATEPART(yyyy,RegDate)
--d3
select convert(varchar,convert(money,isnull(sum(changeSum),0)),1) as re from KFQ_PAY_CHANGE_BILL where DATEPART(mm, GETDATE()) = DATEPART(mm,RegDate) and DATEPART(yyyy, GETDATE()) = DATEPART(yyyy,RegDate)
select * from KFQ_PAY_CHANGE_BILL where DATEPART(qq, GETDATE()) = DATEPART(qq,RegDate) |
REM index_usage.sql
undefine object_name
set pages 99 lines 180 trimspool on pause off
break on object_name skip 1 on object_Secs
column ash_Secs heading 'ASH|Secs' format 999,999
column options format a24
column object_Secs heading 'Object|ASH Secs' format 999,999
column object_name format a18
column module format a32
column num_fms heading 'Num|FMS' format 999,999
column num_sqlids heading 'Num|SQL_IDs' format 999,999
column num_plans heading 'Num|Plans' format 999,999
column num_actions heading 'Num|Actions' format 999,999
spool index_usage.&&object_name..lst
with o as (
select /*+MATERIALIZE*/ DISTINCT object_owner, object_type, object_name
from dba_hist_sql_plan
where object_name like UPPER('&&object_name')
and object_owner = 'SYSADM'
and object_type like 'INDEX%'
), p as (
select /*+MATERIALIZE*/ DISTINCT o.object_owner, o.object_type, o.object_name, p.plan_hash_value, p.options, p.id
from o, dba_hist_sql_plan p
where o.object_name = p.object_name
and o.object_owner = p.objecT_owner
and o.object_type = p.object_type
and p.plan_hash_value > 0
), h as (
select /*+LEADING(i x h)*/ h.sql_plan_hash_value, h.sql_id, h.force_matching_signature, h.sql_plan_line_id
, CASE WHEN h.module like 'PSAE.%' THEN regexp_substr(h.module,'[^@\.]+',1,2)
ELSE regexp_substr(h.module,'[^@]+',1,1) END module
, h.action
, usecs_per_row/1e6 ash_secs
from dba_hist_Active_Sess_history h
, dba_hist_snapshot x
, dba_Hist_database_instance i
where x.dbid = h.dbid
and x.instance_number = h.instance_number
and x.snap_id = h.snap_id
and i.dbid = x.dbid
and i.instance_number = x.instance_number
and i.startup_time = x.startup_time
and not h.module IN('DBMS_SCHEDULER','SQL*Plus')
), x as (
select p.object_name, p.options, h.module, sum(ash_secs) ash_Secs
, count(distinct h.sql_id) num_sqlids
, count(distinct p.plan_hash_value) num_plans
, count(distinct h.force_matching_signature) num_fms
, count(distinct h.action) num_actions
from h, p
where h.sql_plan_hash_value = p.plan_hash_value
and h.sql_plan_line_id = p.id
group by p.object_name, p.options, h.module
)
select o.object_name, x.module, x.options, NVL(x.ash_secs,0) ash_secs
, sum(x.ash_secs) over (partition by o.object_name) objecT_secs
, x.num_fms, x.num_sqlids, x.num_plans, x.num_actions
from o
left outer join x on x.object_name = o.object_name
order by object_secs desc nulls last, object_name, ash_secs desc nulls last
/
spool off
|
/*!40101 SET NAMES binary*/;
/*!40014 SET FOREIGN_KEY_CHECKS=0*/;
/*!40103 SET TIME_ZONE='+00:00' */;
INSERT INTO `wp_term_taxonomy` VALUES
(1,1,"category","",0,1),
(2,2,"category","",0,0),
(3,3,"category","",0,1),
(4,4,"category","",0,0),
(5,5,"category","",0,3),
(6,6,"post_tag","",0,1),
(7,7,"ml-slider","",0,0),
(8,8,"ml-slider","",0,0),
(9,9,"ml-slider","",0,4),
(10,10,"elementor_library_type","",0,2),
(11,11,"nav_menu","",0,9),
(12,12,"post_format","",0,1);
|
-- For details on how to use this report, visit
-- https://modeanalytics.zendesk.com/hc/en-us/articles/203326184
WITH
users AS (
SELECT user_id,
activated_at
FROM tutorial.playbook_users
),
events AS (
SELECT user_id,
event_name,
occurred_at
FROM tutorial.playbook_events
)
SELECT time_id,
{% if metric == 'number of users' %}
home_page_visits_users AS home_page_visits,
searches_users AS shares,
messages_users AS new_chat,
like_message_users AS new_notes,
view_inbox_users AS searches
{% elsif metric == 'number of events' %}
home_page_visits,
searches,
messages,
like_messages,
view_inbox
{% elsif metric == 'average times used per user' %}
home_page_visits/CASE WHEN home_page_visits_users = 0 THEN 1 ELSE home_page_visits_users END::FLOAT AS home_page_visits,
searches/CASE WHEN searches_users = 0 THEN 1 ELSE searches_users END::FLOAT AS searches,
messages/CASE WHEN messages_users = 0 THEN 1 ELSE messages_users END::FLOAT AS messages,
like_message/CASE WHEN like_message_users = 0 THEN 1 ELSE like_message_users END::FLOAT AS like_messages,
view_inbox/CASE WHEN view_inbox_users = 0 THEN 1 ELSE view_inbox_users END::FLOAT AS view_inbox
{% endif %}
FROM (
SELECT DATE_TRUNC('{{time_interval}}',e.occurred_at) AS time_id,
COUNT(DISTINCT CASE WHEN e.event_name = 'home_page' THEN e.user_id ELSE NULL END) AS home_page_visits_users,
COUNT(DISTINCT CASE WHEN e.event_name = 'search_run' THEN e.user_id ELSE NULL END) AS searches_users,
COUNT(DISTINCT CASE WHEN e.event_name = 'send_message' THEN e.user_id ELSE NULL END) AS messages_users,
COUNT(DISTINCT CASE WHEN e.event_name = 'like_message' THEN e.user_id ELSE NULL END) AS like_message_users,
COUNT(DISTINCT CASE WHEN e.event_name = 'view_inbox' THEN e.user_id ELSE NULL END) AS view_inbox_users,
COUNT(CASE WHEN e.event_name = 'home_page' THEN e.user_id ELSE NULL END) AS home_page_visits,
COUNT(CASE WHEN e.event_name = 'search_run' THEN e.user_id ELSE NULL END) AS searches,
COUNT(CASE WHEN e.event_name = 'send_message' THEN e.user_id ELSE NULL END) AS messages,
COUNT(CASE WHEN e.event_name = 'like_message' THEN e.user_id ELSE NULL END) AS like_message,
COUNT(CASE WHEN e.event_name = 'view_inbox' THEN e.user_id ELSE NULL END) AS view_inbox
FROM users u
JOIN events e
ON e.user_id = u.user_id
AND e.occurred_at >= '{{start_date}}'
AND e.occurred_at <= '{{end_date}}'
GROUP BY 1
ORDER BY 1
) z
{% form %}
start_date:
type: text
default: 2014-01-01
end_date:
type: text
default: 2014-10-31
time_interval:
type: select
options: [['day','day'],
['week','week'],
['month','month']]
default: day
metric:
type: select
options: [['number of users','number of users'],
['number of events','number of events'],
['average times used per user','average times used per user']]
default: 'number of users'
{% endform %} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.