text stringlengths 6 9.38M |
|---|
.macro $SYS sys
movl $\sys, %eax
int $0x80
.endm
.macro $SYS1 sys, p1
movl \p1, %ebx
$SYS \sys
.endm
.macro $SYS2 sys, p1, p2
movl \p2, %ecx
$SYS1 \sys, \p1
.endm
.macro $SYS3 sys, p1, p2, p3
movl \p3, %edx
$SYS2 \sys, \p1, \p2
.endm
.macro $SYS4 sys, p1, p2, p3, p4
mov \p4, %esi
$SYS3 \sys, \p1, \p2, \p3
.endm
.macro $SYS5 sys, p1, p2, p3, p4, p5
mov \p5, %edi
$SYS4 \sys, \p1, \p2, \p3, \p4
.endm
.macro $SYS6 sys, p1, p2, p3, p4, p5, p6
mov \p6, %ebp
$SYS5 \sys, \p1, \p2, \p3, \p4, \p5
.endm
|
--------------------------------------------------------
-- DDL for Trigger TU_TORRE_FRETES
--------------------------------------------------------
CREATE OR REPLACE TRIGGER "VND"."TU_TORRE_FRETES" BEFORE UPDATE ON VND.ELO_CARTEIRA
REFERENCING NEW AS new FOR EACH ROW
DECLARE
V_CUSTOMER_SERVICE_NEW NUMBER;
V_CUSTOMER_SERVICE_PRO NUMBER;
V_CUSTOMER_SERVICE_FIN NUMBER;
BEGIN
BEGIN
SELECT I_ST_NEW_PRO.CD_ELO_STATUS INTO V_CUSTOMER_SERVICE_NEW
FROM VND.ELO_STATUS I_ST_NEW_PRO
INNER JOIN VND.ELO_TIPO_STATUS I_ST_TIPO_NP
ON
I_ST_NEW_PRO.CD_ELO_TIPO_STATUS = I_ST_TIPO_NP.CD_ELO_TIPO_STATUS
WHERE
I_ST_NEW_PRO.SG_STATUS IN('CANEW')
AND I_ST_TIPO_NP.SG_TIPO_STATUS = 'CARTE' ;
EXCEPTION
WHEN OTHERS THEN
V_CUSTOMER_SERVICE_NEW:= NULL;
END;
BEGIN
SELECT I_ST_NEW_PRO.CD_ELO_STATUS INTO V_CUSTOMER_SERVICE_PRO
FROM VND.ELO_STATUS I_ST_NEW_PRO
INNER JOIN VND.ELO_TIPO_STATUS I_ST_TIPO_NP
ON
I_ST_NEW_PRO.CD_ELO_TIPO_STATUS = I_ST_TIPO_NP.CD_ELO_TIPO_STATUS
WHERE
I_ST_NEW_PRO.SG_STATUS IN('CAPRO')
AND I_ST_TIPO_NP.SG_TIPO_STATUS = 'CARTE' ;
EXCEPTION
WHEN OTHERS THEN
V_CUSTOMER_SERVICE_PRO:= NULL;
END;
BEGIN
SELECT I_ST_NEW_PRO.CD_ELO_STATUS INTO V_CUSTOMER_SERVICE_FIN
FROM VND.ELO_STATUS I_ST_NEW_PRO
INNER JOIN VND.ELO_TIPO_STATUS I_ST_TIPO_NP
ON
I_ST_NEW_PRO.CD_ELO_TIPO_STATUS = I_ST_TIPO_NP.CD_ELO_TIPO_STATUS
WHERE
I_ST_NEW_PRO.SG_STATUS IN('CAFIN')
AND I_ST_TIPO_NP.SG_TIPO_STATUS = 'CARTE' ;
EXCEPTION
WHEN OTHERS THEN
V_CUSTOMER_SERVICE_FIN:= NULL;
END;
IF :new.CD_STATUS_TORRE_FRETES = V_CUSTOMER_SERVICE_PRO AND
NOT(:new.CD_STATUS_CUSTOMER_SERVICE = :old.CD_STATUS_CUSTOMER_SERVICE AND
:new.CD_STATUS_TORRE_FRETES = :old.CD_STATUS_TORRE_FRETES AND
:new.IC_PERMITIR_CS = :old.IC_PERMITIR_CS AND
:new.SG_DESTINO_BACKLOG_CIF = :old.SG_DESTINO_BACKLOG_CIF ) THEN
:new.DH_MODIFICACAO_TORRE_FRETES:= CURRENT_DATE;
:new.DH_CONTRATACAO_TORRE_FRETES:= CURRENT_DATE;
END IF;
IF :new.SG_DESTINO_BACKLOG_CIF IS NOT NULL AND
:new.CD_ELO_CARTEIRA_GROUPING IS NOT NULL AND
(:new.SG_DESTINO_BACKLOG_CIF IS NOT NULL AND NVL(TRIM(:old.SG_DESTINO_BACKLOG_CIF), '') = '' ) THEN
:new.DH_BACKLOG_CIF:= CURRENT_DATE;
END IF;
IF :new.CD_STATUS_TORRE_FRETES = V_CUSTOMER_SERVICE_PRO OR :new.CD_STATUS_TORRE_FRETES = V_CUSTOMER_SERVICE_NEW AND
:new.CD_ELO_CARTEIRA_GROUPING IS NOT NULL AND :new.CD_STATUS_CUSTOMER_SERVICE IS NOT NULL THEN
:new.CD_STATUS_CUSTOMER_SERVICE:= V_CUSTOMER_SERVICE_FIN;
:new.NU_PROTOCOLO_ENTREGA:= 'SCS:)' || TO_CHAR(CURRENT_DATE, 'YYYY-MM-DD HH:MI');
END IF;
END;
/
ALTER TRIGGER "VND"."TU_TORRE_FRETES" ENABLE;
|
ALTER TABLE CRASH.OUTPUTS
ALTER COLUMN STDOUT SET DATA TYPE OID USING lo_from_bytea(0, STDOUT),
ALTER COLUMN STDERR SET DATA TYPE OID USING lo_from_bytea(0, STDERR),
ALTER COLUMN PROFILE_FILE SET DATA TYPE OID USING lo_from_bytea(0, PROFILE_FILE),
ALTER COLUMN MACHINE_INFO SET DATA TYPE OID USING lo_from_bytea(0, MACHINE_INFO),
ALTER COLUMN STACKTRACE SET DATA TYPE OID USING lo_from_bytea(0, STACKTRACE); |
-- MySQL dump 10.13 Distrib 5.5.12, for solaris10 (i386)
--
-- Host: sql Database: p_acc_live
-- ------------------------------------------------------
-- Server version 5.1.66
/*!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 latin1 */;
/*!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 `acc_ban`
--
DROP TABLE IF EXISTS `acc_ban`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `acc_ban` (
`ban_id` int(11) NOT NULL AUTO_INCREMENT,
`ban_type` varchar(255) NOT NULL,
`ban_target` varchar(700) NOT NULL,
`ban_user` varchar(255) NOT NULL,
`ban_reason` varchar(4096) NOT NULL,
`ban_date` varchar(1024) NOT NULL,
`ban_duration` varchar(255) NOT NULL,
`ban_active` tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`ban_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3356 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `acc_cmt`
--
DROP TABLE IF EXISTS `acc_cmt`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `acc_cmt` (
`cmt_id` int(11) NOT NULL AUTO_INCREMENT,
`cmt_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`cmt_user` varchar(255) NOT NULL,
`cmt_comment` mediumtext NOT NULL,
`cmt_visability` varchar(255) NOT NULL,
`pend_id` int(11) NOT NULL,
PRIMARY KEY (`cmt_id`),
UNIQUE KEY `cmt_id` (`cmt_id`)
) ENGINE=InnoDB AUTO_INCREMENT=17577 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `acc_emails`
--
DROP TABLE IF EXISTS `acc_emails`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `acc_emails` (
`mail_id` int(11) NOT NULL AUTO_INCREMENT,
`mail_text` blob NOT NULL,
`mail_count` int(11) NOT NULL,
`mail_desc` varchar(255) NOT NULL,
`mail_type` varchar(255) NOT NULL,
PRIMARY KEY (`mail_id`)
) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `acc_log`
--
DROP TABLE IF EXISTS `acc_log`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `acc_log` (
`log_id` int(11) NOT NULL AUTO_INCREMENT,
`log_pend` varchar(255) NOT NULL,
`log_user` varchar(255) NOT NULL,
`log_action` varchar(255) NOT NULL,
`log_time` datetime NOT NULL,
`log_cmt` blob NOT NULL,
PRIMARY KEY (`log_id`),
KEY `acc_log_action_idx` (`log_action`),
KEY `log_pend_idx` (`log_pend`)
) ENGINE=InnoDB AUTO_INCREMENT=142146 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `acc_pend`
--
DROP TABLE IF EXISTS `acc_pend`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `acc_pend` (
`pend_id` int(11) NOT NULL AUTO_INCREMENT,
`pend_email` varchar(512) NOT NULL,
`pend_ip` varchar(255) NOT NULL,
`pend_name` varchar(512) NOT NULL,
`pend_cmt` mediumtext NOT NULL,
`pend_status` varchar(255) NOT NULL,
`pend_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`pend_checksum` varchar(256) NOT NULL,
`pend_emailsent` varchar(10) NOT NULL,
`pend_mailconfirm` varchar(255) NOT NULL,
`pend_reserved` int(11) NOT NULL DEFAULT '0' COMMENT 'User ID of user who has "reserved" this request',
`pend_useragent` blob NOT NULL COMMENT 'Useragent of the requesting web browser',
`pend_proxyip` varchar(255) DEFAULT NULL,
PRIMARY KEY (`pend_id`),
KEY `acc_pend_status_mailconf` (`pend_status`,`pend_mailconfirm`),
KEY `pend_ip_status` (`pend_ip`,`pend_mailconfirm`),
KEY `pend_email_status` (`pend_email`,`pend_mailconfirm`),
KEY `ft_useragent` (`pend_useragent`(512))
) ENGINE=InnoDB AUTO_INCREMENT=85511 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `acc_template`
--
DROP TABLE IF EXISTS `acc_template`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `acc_template` (
`template_id` int(11) NOT NULL AUTO_INCREMENT,
`template_usercode` tinytext NOT NULL,
`template_botcode` tinytext NOT NULL,
PRIMARY KEY (`template_id`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `acc_titleblacklist`
--
DROP TABLE IF EXISTS `acc_titleblacklist`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `acc_titleblacklist` (
`titleblacklist_regex` varchar(128) NOT NULL,
`titleblacklist_casesensitive` tinyint(1) NOT NULL,
PRIMARY KEY (`titleblacklist_regex`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `acc_trustedips`
--
DROP TABLE IF EXISTS `acc_trustedips`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `acc_trustedips` (
`trustedips_ipaddr` varchar(15) NOT NULL,
PRIMARY KEY (`trustedips_ipaddr`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `acc_user`
--
DROP TABLE IF EXISTS `acc_user`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `acc_user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) NOT NULL,
`user_email` varchar(255) NOT NULL,
`user_pass` varchar(255) NOT NULL,
`user_level` varchar(255) NOT NULL DEFAULT 'New',
`user_onwikiname` varchar(255) NOT NULL,
`user_welcome_sig` varchar(4096) NOT NULL DEFAULT '',
`user_welcome_template` varchar(1024) NOT NULL DEFAULT '0',
`user_lastactive` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`user_lastip` varchar(40) CHARACTER SET utf8 NOT NULL DEFAULT '0.0.0.0',
`user_forcelogout` int(3) NOT NULL DEFAULT '0',
`user_secure` int(11) NOT NULL DEFAULT '0',
`user_checkuser` int(1) NOT NULL DEFAULT '0',
`user_identified` int(1) unsigned NOT NULL DEFAULT '0',
`user_welcome_templateid` int(11) NOT NULL DEFAULT '0',
`user_abortpref` tinyint(4) NOT NULL DEFAULT '0',
`user_confirmationdiff` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`user_id`),
UNIQUE KEY `I_username` (`user_name`) USING BTREE,
UNIQUE KEY `user_onwikiname_UNIQUE` (`user_onwikiname`),
UNIQUE KEY `user_email_UNIQUE` (`user_email`)
) ENGINE=InnoDB AUTO_INCREMENT=878 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `acc_welcome`
--
DROP TABLE IF EXISTS `acc_welcome`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `acc_welcome` (
`welcome_id` int(11) NOT NULL AUTO_INCREMENT,
`welcome_uid` varchar(1024) NOT NULL,
`welcome_user` varchar(1024) NOT NULL,
`welcome_sig` varchar(4096) NOT NULL,
`welcome_status` varchar(96) NOT NULL,
`welcome_pend` int(11) NOT NULL,
`welcome_template` varchar(2048) NOT NULL,
PRIMARY KEY (`welcome_id`)
) ENGINE=InnoDB AUTO_INCREMENT=35062 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `closes`
--
DROP TABLE IF EXISTS `closes`;
/*!50001 DROP VIEW IF EXISTS `closes`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE TABLE `closes` (
`CONCAT("Closed ",mail_id)` varbinary(45),
`mail_desc` varchar(255)
) ENGINE=MyISAM */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `createdusers`
--
DROP TABLE IF EXISTS `createdusers`;
/*!50001 DROP VIEW IF EXISTS `createdusers`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE TABLE `createdusers` (
`pend_name` varchar(512)
) ENGINE=MyISAM */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `id`
--
DROP TABLE IF EXISTS `id`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `id` (
`enwikiname` varchar(50) NOT NULL,
PRIMARY KEY (`enwikiname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `logactions`
--
DROP TABLE IF EXISTS `logactions`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `logactions` (
`action` varchar(45) NOT NULL,
`number` int(11) DEFAULT NULL,
PRIMARY KEY (`action`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Final view structure for view `closes`
--
/*!50001 DROP TABLE IF EXISTS `closes`*/;
/*!50001 DROP VIEW IF EXISTS `closes`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8 */;
/*!50001 SET character_set_results = utf8 */;
/*!50001 SET collation_connection = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`acc`@`%.toolserver.org` SQL SECURITY DEFINER */
/*!50001 VIEW `closes` AS select concat('Closed ',`acc_emails`.`mail_id`) AS `CONCAT("Closed ",mail_id)`,`acc_emails`.`mail_desc` AS `mail_desc` from `acc_emails` where (`acc_emails`.`mail_type` = 'Message') union select 'Closed 0' AS `Closed 0`,'Dropped' AS `Dropped` union select 'Closed custom' AS `Closed custom`,'Closed custom' AS `Closed custom` union select 'Closed custom-n' AS `Closed custom-n`,'Closed custom - Not created' AS `Closed custom - Not created` union select 'Closed custom-y' AS `Closed custom-y`,'Closed custom - Created' AS `Closed custom - Created` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `createdusers`
--
/*!50001 DROP TABLE IF EXISTS `createdusers`*/;
/*!50001 DROP VIEW IF EXISTS `createdusers`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8 */;
/*!50001 SET character_set_results = utf8 */;
/*!50001 SET collation_connection = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`acc`@`%.toolserver.org` SQL SECURITY DEFINER */
/*!50001 VIEW `createdusers` AS select distinct `acc_pend`.`pend_name` AS `pend_name` from (`acc_log` join `acc_pend` on((`acc_pend`.`pend_id` = `acc_log`.`log_pend`))) where (`acc_log`.`log_action` = 'Closed 1') order by `acc_pend`.`pend_name` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2012-12-23 3:56:29
|
alter table if exists COMPANIES_COMPANY_NAMES drop constraint if exists FK7dplmqp7bb1m74fik1aoxy0yq
alter table if exists COMPANIES_COMPANY_NAMES drop constraint if exists FKn3qhtm3r4eu9cd78si05xrv5h
alter table if exists ORGANIZATION_UNITS drop constraint if exists FKc36lxm5lc90vm1kque8vr7cyd
alter table if exists ORGANIZATION_UNITS drop constraint if exists FKaxl5lltie4tsoy0wug3btb5hl
alter table if exists ORGANIZATION_UNITS_ORGANIZATION_UNIT_NAMES drop constraint if exists FKpqciiy5y9smeeod0xvanq6wfg
alter table if exists ORGANIZATION_UNITS_ORGANIZATION_UNIT_NAMES drop constraint if exists FKciddj53m25d6p61rhine0fvbo
alter table if exists ORGANIZATIONS drop constraint if exists FKpl7c9r2u24rjr6pqmrcd9mxdq
alter table if exists USER_ROLES drop constraint if exists FKk3qtke64s9k5pv5hoq6yyq7py
alter table if exists USERS drop constraint if exists FKdeidj66mcx6k8vsoflveak3gj
drop table if exists CHANGE_USERS cascade
drop table if exists COMPANIES cascade
drop table if exists COMPANIES_COMPANY_NAMES cascade
drop table if exists COMPANY_NAMES cascade
drop table if exists DATETIMES cascade
drop table if exists INQUIRIES cascade
drop table if exists ORGANIZATION_UNIT_NAMES cascade
drop table if exists ORGANIZATION_UNITS cascade
drop table if exists ORGANIZATION_UNITS_ORGANIZATION_UNIT_NAMES cascade
drop table if exists ORGANIZATIONS cascade
drop table if exists REGIST_USERS cascade
drop table if exists RESET_USERS cascade
drop table if exists USER_ROLES cascade
drop table if exists USERS cascade
drop sequence if exists hibernate_sequence
|
-- Drops the FitMe if it exists currently --
DROP DATABASE IF EXISTS FitMe;
-- Creates the "FitMe" database --
CREATE DATABASE FitMe;
USE FitMe;
CREATE TABLE Activity(
id INT AUTO_INCREMENT,
activity_name VARCHAR(100),
PRIMARY KEY(id)
);
CREATE TABLE user(
id INT AUTO_INCREMENT,
First_name VARCHAR(40),
Password Varchar(40),
PRIMARY KEY (id)
);
CREATE TABLE user_log (
id INT AUTO_INCREMENT,
users INT,
body VARCHAR (300),
logged_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
activity_id INT,
PRIMARY KEY (users),
FOREIGN KEY(activity_id) REFERENCES Activity(id),
FOREIGN KEY (users) REFERENCES user(id)
)
|
--涨工资,总裁1000 经理800 其他400
set serveroutput on
declare
--alter table "SCOTT"."EMP" rename column "JOB" to empjob
cursor cemp is select empno,empjob from emp;
pempno emp.empno%type;
pjob emp.empjob%type;
begin
rollback;
open cemp;
loop
--取一条记录
fetch cemp into pempno,pjob;
exit when cemp%notfound;
--判断职位
if pjob = 'PRESIDENT' then update emp set sal=sal+1000 where empno=pempno;
elsif pjob = 'MANAGER' then update emp set sal=sal+800 where empno=pempno;
else update emp set sal=sal+400 where empno=pempno;
end if;
end loop;
close cemp;
--why? --> ACID
commit;
dbms_output.put_line('完成');
end;
/
|
CREATE DATABASE app;
\c app;
CREATE EXTENSION "pgcrypto";
CREATE TABLE workflow (
id UUID NOT NULL DEFAULT gen_random_uuid(),
status int,
data json,
steps json
); |
-- CS3200: Database Design
-- Homework #2: Genes and Disease
-- Create a new schema called "gad"
-- Then use the data import wizard to load the data "gad.csv" into a new table, also called "gad"
-- Remember to change the inferred datatype for the chromosome field from INT to TEXT
-- You should end up with a table containing 39,910 records
-- Write a query to answer each of the following questions
-- Save your script file as cs3200_hw2_lastname.sql
-- Submit this file for your homework submission
USE gad;
-- 1a. (2.5 points)
-- Write a query that verifies that you have imported 39,910 records
SELECT (SELECT COUNT(*)
FROM gad) = 39910;
-- 1b. (2.5 points)
-- Write a query that lists the different columns in your gad table
-- Include a comment explaining why it was necessary to change the chromosome to a text field.
SHOW COLUMNS FROM gad;
-- The field chromosome is the label of a gene showing where it comes from,
-- but not a numerical property of the data entry.
-- We don't want to compare the value but just use this label to differ from other genes.
-- 2. (5 points)
-- What are the distinct disease classes referenced in this data?
-- Output your list in alphabetical order
SELECT DISTINCT disease_class
FROM gad
ORDER BY disease_class ASC;
-- 3. (5 points)
-- List all distinct phenotypes related to the disease class "IMMUNE"
-- Output your list in alphabetical order
SELECT DISTINCT phenotype
FROM gad
WHERE disease_class = 'IMMUNE'
ORDER BY phenotype ASC;
-- 4. (5 points)
-- List the gene symbol, gene name, and chromosome attributes related
-- to genes positively linked to asthma (association = Y).
-- Count any phenotype containing the substring "asthma"
-- List each distinct record once
-- Sort by gene symbol
SELECT DISTINCT gene, gene_name, chromosome
FROM gad
WHERE association = 'Y' AND phenotype LIKE '%asthma%'
ORDER BY gene ASC;
-- 5. (5 points)
-- Explore the content of the various columns in your gad table.
-- List all genes that are "G protein-coupled" receptors in alphabetical order by gene symbol
-- Output the gene symbol, gene name, and chromosome
-- (These genes are often the target for new drugs, so are of particular interest)
SELECT gene, gene_name, chromosome
FROM gad
WHERE gene_name LIKE '%G protein-coupled%'
ORDER BY gene;
-- 6. (5 points)
-- For genes on chromosome 3, what is the minimum, maximum DNA location
-- Exclude cases where the dna_start value is 0
SELECT MIN(dna_start) AS 'minimum DNA location',
MAX(dna_end) AS 'maximum DNA location'
FROM gad
WHERE dna_start <> 0;
-- 7 (10 points)
-- For each gene, what is the earliest and latest reported year
-- involving a positive association
-- Ignore records where the year isn't valid. (Explore the year column to determine what constitutes a valid year.)
-- Output the gene, min-year, max-year, and number of GAD records
-- order by min-year, max-year, gene-name (3-level sorting)
SELECT gene,
gene_name,
MIN(year) AS 'min_year',
MAX(year) AS 'max_year',
COUNT(*)
FROM gad
WHERE year > 1900
GROUP BY gene, gene_name
ORDER BY min_year, max_year, gene_name;
-- 8. (10 points)
-- How many records are there for each gene?
-- Output the gene symbol and name and the count of the number of records
-- Order by the record count in descending order
SELECT gene, gene_name, COUNT(*) AS 'record_count'
FROM gad
GROUP BY gene, gene_name
ORDER BY record_count desc;
-- 9. (10 points)
-- Modify query 8 by considering only positive associations
-- and limit output to records having at least 100 associations
SELECT gene, gene_name, COUNT(*) AS 'record_count'
FROM gad
WHERE association = 'Y'
GROUP BY gene, gene_name
HAVING record_count >= 100
ORDER BY record_count DESC;
-- 10. (10 points)
-- How many total GAD records are there for each population group?
-- Sort in descending order by count
-- Show only the top five records
-- Do NOT include cases where the population is blank
SELECT population, COUNT(*) AS count
FROM gad
WHERE population <> ""
GROUP BY population
ORDER BY count DESC
LIMIT 5;
-- 11. (10 points)
-- In question 4, we found asthma-linked genes
-- But these genes might also be implicated in other diseases
-- Output gad records involving a positive association between ANY asthma-linked gene and ANY disease/phenotype
-- Sort your output alphabetically by phenotype
-- Output the gene, gene_name, association (should always be 'Y'), phenotype, disease_class, and population
-- Hint: Use a subselect in your WHERE class and the IN operator
SELECT gene, gene_name, association, phenotype, disease_class, population
FROM gad
WHERE gene IN (SELECT distinct gene
FROM gad
WHERE phenotype LIKE "%asthma%")
AND association = 'Y'
ORDER BY phenotype ASC;
-- 12. (10 points)
-- Modify your previous query.
-- Let's count how many times each of these asthma-gene-linked phenotypes occurs
-- in our output table produced by the previous query.
-- Output just the phenotype, and a count of the number of occurrences for the top 5 phenotypes
-- with the most records involving an asthma-linked gene (EXCLUDING asthma itself).
SELECT phenotype, COUNT(*) as 'count'
FROM gad
WHERE gene IN (SELECT distinct gene
FROM gad
WHERE phenotype LIKE "%asthma%")
AND association = 'Y'
AND phenotype <> 'asthma'
GROUP BY phenotype
ORDER BY count DESC
Limit 5;
-- 13. (10 points)
-- Interpret your analysis
-- Do an internet search and answer the following questions - (You can put your answer right into this script as comments.)
-- a) Does existing biomedical research support a connection between asthma and the disease you identified above?
-- 1. For type1 diabetes, some study suggest that "a prior diagnosis of asthma increases the risk of subsequent type 1 diabetes".
-- However, some more recent study also suggest that type 1 diabetes diagnosis first decreases the risk of subsequent asthma.
-- source: https://www.patientcareonline.com/view/asthma-diagnosis-associated-type-1-diabetes
-- 2. For lung cancer, a study published on Oncotarget suggest that "prior asthma is significantly associated with lung cancer risk".
-- This result is shown to be corrected in race groups including Caucasians and Asians. Also, both male and female patients with
-- asthma "showed increased risk for lung cancer".
-- source: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5355290/
-- 3. For rheumatoid arthritis, a literature review in Tuberculosis & Respiratory Diseases indicates a strong relation between these
-- two diseases. source: https://www.rheumatologyadvisor.com/home/topics/rheumatoid-arthritis/rheumatoid-arthritis-and-asthma-is-there-a-link/
-- 4. For hypertension, a research from the New England Journal of Medicien suggest that there is a potential mechanistic links between hypertension
-- and asthma. source: https://www.nejm.org/doi/full/10.1056/NEJMra1800345
-- 5. For breast cancer, there is an artical from Cancer Cause Control showing that there is no statistically significant
-- relation between the two diseases.
-- source: https://www.ncbi.nlm.nih.gov/pubmed/23443321
-- b) Why might a drug company be interested in instances of such "overlapping" phenotypes?
-- Some exisiting drug might help treat the related diseases. Also, the underlying mechanism of the two diseases might have some relations.
-- Thus help the development of the drug that treat the related diseases.
-- CONGRATULATIONS!!: YOU JUST DID SOME LEGIT DRUG DISCOVERY RESEARCH! :-)
|
SELECT
da.[AttributeValue]
,bh.*
FROM [hist].[Backups_History_vw] bh
INNER JOIN [hist].[ServerInventory_SQL_DatabaseAttributes_vw] da
ON bh.[ServerName] = da.[ServerName]
AND bh.[DatabaseName] = da.[DBName]
WHERE bh.[ServerName] = 'UHVSQLMAN01'
AND bh.[DatabaseName] = 'DBACentral'
AND da.[AttributeName] = 'recovery_model_desc'
AND
(
CASE -- If there was a tlog backup on a db that is no longer in SIMPLE, remove it
WHEN da.[AttributeValue] = 'SIMPLE' AND bh.[BackupType] = 'L' THEN 0
ELSE 1
END
) = 1
ORDER BY [StartDate] |
-- Criar uma tabela para guardar as notas dos alunos.
-- Cada curso é composto por 4 notas e a situação final, aprovado/reprovado
-- é definida pela média aritmétiva das 4 notas.
-- Atualizar tabela item, adicionando campo id como pk e tirar pk dos campos
-- contrato_id, curso_id.
-- Popular campos id com número sequencial único.1
-- criação da tabela nota
CREATE TABLE nota (
id INTEGER NOT NULL,
item_id INTEGER NOT NULL,
nota NUMBER(5, 2) NOT NULL
);
ALTER TABLE nota ADD CONSTRAINT nota_pk PRIMARY KEY ( id );
ALTER TABLE nota
ADD CONSTRAINT nota_item_fk FOREIGN KEY ( item_id )
REFERENCES item ( id );
-- verificar se existe contrato_id, curso_id repetidos em item
-- e excluir todas as linhas que estão repetidas.
DELETE FROM ITEM IT
WHERE LPAD(CONTRATO_ID, 3, 0) || LPAD(CURSO_ID, 3, 0) IN
(
SELECT
LPAD(CONTRATO_ID, 3, 0) || LPAD(CURSO_ID, 3, 0) CHAVE
FROM ITEM IT
GROUP BY LPAD(CONTRATO_ID, 3, 0) || LPAD(CURSO_ID, 3, 0)
HAVING COUNT(1) > 1
);
COMMIT;
SELECT
AL.NOME ALUNO,
CO.ID CONTRATO_ID,
CO.DATA_INICIO, CO.DATA_FIM,
CS.ID CURSO_ID,
CS.NOME CURSO
FROM ALUNO AL
INNER JOIN
CONTRATO CO ON (AL.ID = CO.ALUNO_ID)
INNER JOIN
ITEM IT ON (CO.ID = IT.CONTRATO_ID)
INNER JOIN
CURSO CS ON (IT.CURSO_ID = CS.ID)
WHERE
CS.ID = 74 AND
CO.ID = 270
ORDER BY 2, 5;
-- teste de insert com sequencial
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 512,150);
COMMIT;
-- inserindo registro unicos na tabela item;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 328,120);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 71,84);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 422,135);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 280,218);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 824,224);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 590,33);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 620,103);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 986,96);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 528,67);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 245,44);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 929,148);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 466,12);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 959,105);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 94,149);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 152,55);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 497,228);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 581,12);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 636,135);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 755,166);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 152,102);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 169,226);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 814,162);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 144,45);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 184,135);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 398,87);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 536,149);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 565,193);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 815,73);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 281,177);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 392,40);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 45,170);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 925,204);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 270,74);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 238,161);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 626,190);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 481,238);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 422,222);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 332,128);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 765,155);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 470,6);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 781,211);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 240,164);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 331,228);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 869,22);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 987,90);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 284,56);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 66,213);
COMMIT;
INSERT INTO ITEM(ID, CONTRATO_ID, CURSO_ID) VALUES ((SELECT MAX(ID) + 1 FROM ITEM), 955,207);
COMMIT;
-- criando constraint na tabela item
ALTER TABLE item
ADD CONSTRAINT item_contrato_curso_un
UNIQUE ( contrato_id, curso_id );
-- CONTRATO_ID, CURSO_ID, QTDE
-- 328 120 02
-- 071 084 03
-- 422 135 02
-- 280 218 02
-- 824 224 02
-- 590 033 02
-- 620 103 02
-- 986 096 03
-- 528 067 02
-- 245 044 02
-- 929 148 02
-- 466 012 02
-- 959 105 02
-- 094 149 02
-- 152 055 02
-- 497 228 02
-- 581 012 02
-- 636 135 02
-- 755 166 02
-- 152 102 02
-- 169 226 02
-- 814 162 02
-- 144 045 02
-- 512 150 02
-- 184 135 02
-- 398 087 02
-- 536 149 02
-- 565 193 02
-- 815 073 02
-- 281 177 02
-- 392 040 02
-- 045 170 02
-- 925 204 02
-- 270 074 02
-- 238 161 02
-- 626 190 02
-- 481 238 02
-- 422 222 02
-- 332 128 02
-- 765 155 02
-- 470 006 02
-- 781 211 02
-- 240 164 02
-- 331 228 02
-- 869 022 02
-- 987 090 02
-- 284 056 02
-- 066 213 02
-- 955 207 02
SELECT ITEM_ID, AVG(NOTA) FROM NOTA
GROUP BY ITEM_ID
HAVING AVG(NOTA) > 7
ORDER BY 2 DESC;
SELECT * FROM ITEM;
-- inserindo registros em uma tabela a partir de um select
-- com sub-consulta.
INSERT INTO NOTA (ID, ITEM_ID, NOTA)
SELECT ROWNUM ID, ITEM_ID, NOTA FROM (
SELECT ID ITEM_ID, ROUND(DBMS_RANDOM.VALUE(1, 10), 2) NOTA
FROM ITEM IT, (SELECT ROWNUM SEQ FROM ALUNO WHERE ROWNUM <= 4) B
ORDER BY 1
)
COMMIT;
|
#between x and y 在某两个数值之间包含and两边的数值
#1.查询员工工资500-1000的所有员工名字和工资
SELECT ename,sal FROM emp WHERE sal >= 500 AND sal <= 1000;
SELECT ename,sal FROM emp WHERE sal BETWEEN 500 AND 1000;
#like 模糊查询 _代表单个位置的字符 %代表多个未知的字符
#2.查询名字以k开头的所有名字开头的员工名字
SELECT ename FROM emp WHERE ename LIKE "k%" ;
#3.查询名字第二个字母是m的所有员工名字
SELECT ename FROM emp WHERE ename LIKE "_m%";
#4.查询名字第三个字母是l的所有员工名字
SELECT ename FROM emp WHERE ename LIKE "__l%";
#5.查询名字倒数第二个字母是e的所有员工名字
SELECT ename FROM emp WHERE ename LIKE "%e_";
#6.查询单价低于100的记事本t_item
SELECT title,price FROM t_item WHERE price < 100 AND title LIKE "%记事本%";
#7.查询商品标题包含笔记本的商品
SELECT title FROM t_item WHERE title LIKE "%记事本%";
#8.查询有图片的得力商品
SELECT title FROM t_item WHERE title LIKE "%得力%" AND image IS NOT NULL;
#9.查询单价介于50-200之间的得力商品
SELECT title,price FROM t_item WHERE title LIKE "%得力%" AND price BETWEEN 50 AND 200;
#10.查询有赠品的得力商品
SELECT title FROM t_item WHERE title LIKE "%得力%" AND sell_point LIKE "%赠%";
#查询结果排序 order by 默认升序 指定升序asc 指定降序 desc
#11.查询员工的名称和工资,按照工资降序排序
SELECT ename,sal FROM emp ORDER BY sal DESC;
#12.查询单价在100以下的商品名称和价格,并按降序排列
SELECT title,price FROM t_item WHERE price < 100 ORDER BY price DESC;
#13.查询单价在100以下的记事本商品的名称和单价并升序排列
SELECT title,price FROM t_item WHERE title LIKE "%记事本%" AND price < 100 ORDER BY price;
#多个字段排序 当第1个字段有相同值时 第二个字段排序开始
#14.查询所有部门编号工资部门编号降序,工资升序
SELECT deptno,sal FROM emp ORDER BY deptno ASC,sal DESC;
#15查询记事本商品的名字价格,价格在30-100,按照商品的分类降序排列,价格升序排列
SELECT price,title,category_id FROM t_item WHERE title LIKE "%记事本%" AND price BETWEEN 30 AND 100 ORDER BY category_id DESC,price ASC;
#limit 分页查询
#跳过条数,查询条数 例如:每一页显示a条第y页则是limit a(x-1),y
#查询商品表中商品名称和价格第一页数据,每一页显示五条
SELECT title,price FROM t_item LIMIT 0,5;
#查询商品表中商品名称和价格第三页数据,每一页显示六条
SELECT title,price FROM t_item LIMIT 12,6;
#查询最高工资的员工信息
SELECT * FROM emp ORDER BY sal DESC LIMIT 0,1;
#查询第二个字母时l,工资小于等于两千多前两名员工信息
SELECT * FROM emp WHERE sal < 2000 ORDER BY sal DESC LIMIT 0,2;
#数值计算 +-*/%(mod)
#查询所有商品的单价,库存,总价
SELECT price,num,price * num "总价" FROM t_item;
# % mod都是取余作用
SELECT (8 % 3);
SELECT (8 MOD 3);
#day03
#日期相关函数
#获取当前时间日期 now()
SELECT NOW();
#获取当前日期 curdate()
SELECT CURDATE();
#获取当前时间 curtime();
SELECT CURTIME();
#从日期中提取时间
SELECT TIME(NOW());
#从日期中提取日期
SELECT DATE(NOW());
#1.查询商品创建的年月日
SELECT DATE(created_time) FROM t_item;
#2.查询商品的创建时间
SELECT TIME(created_time) FROM t_item;
#extract()函数用于返回日期/时间的单独部分,比如年月日时分秒 extract(unit from date)
#提取年
SELECT EXTRACT(YEAR FROM NOW());
#提取月
SELECT EXTRACT(MONTH FROM NOW());
#提取日
SELECT EXTRACT(DAY FROM NOW());
#提取时
SELECT EXTRACT(HOUR FROM NOW());
#提取分
SELECT EXTRACT(MINUTE FROM NOW());
#提取秒
SELECT EXTRACT(SECOND FROM NOW());
#3.查询入职的年份的员工的名字和年份
SELECT ename,EXTRACT(YEAR FROM hiredada) AS "年份" FROM emp;
#日期格式化 date_format(时间 格式)
# %Y:年份 %m:月份 %d:日 %H:时 %
#4.查询现在的时间
SELECT DATE_FORMAT (NOW(),"%Y-%m-%d %H:%i:%s")"当前时间";
#5.查询商品的创建时间年月日
SELECT DATE_FORMAT(created_time,"%Y-%m-%d %H:%i:%s") "创建时间" FROM t_item;
#6.把不规则的日期格式转为标准格式
SELECT STR_TO_DATE("23号10月2020年")
#ifnull() 格式age = ifnull(x,y) 判断x是否为null如果是返回null如果不是则返回age = y
#7.查询员工没有奖金的显示为0;
SELECT ename,IFNULL(comm,0) "奖金" FROM emp;
#8.把员工没有奖金的这些员工的奖金修改为0
UPDATE emp SET comm = IFNULL(comm,0);
#聚合函数 : 对多行数据进行合并统计
#sum() 函数返回数值列的总和
#avg() 函数返回数值列的平均值 null值不包含在计算内
#count() count(column name)函数返回指定列的值的数据,null值不计入
#max()函数返回一列中的最大值
#min()函数返回一列中的最小值
#9.查询员工的平均工资
SELECT AVG(sal) FROM emp;
#10.查询10号部门的最高工资
SELECT deptno,MAX(sal) FROM emp WHERE deptno = 10;
#11.查询dell商品的库存总和
SELECT title,SUM(num) FROM t_item WHERE title LIKE "%Dell%" ;
#12.查询得力商品的条数
SELECT COUNT(title) FROM t_item WHERE title LIKE "%得力%";
#13.查询员工姓名包含a的最低工资
SELECT ename,MIN(sal) FROM emp WHERE ename LIKE "%a%"; |
/*
Copyright 2021 Snowplow Analytics Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
CREATE OR REPLACE TABLE {{.scratch_schema}}.page_views_join_staged{{.entropy}}
AS (
WITH link_clicks AS (
SELECT
page_view_id,
COUNT(event_id) OVER (
PARTITION BY page_view_id
ORDER BY derived_tstamp DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
AS link_clicks,
FIRST_VALUE(unstruct_event_com_snowplowanalytics_snowplow_link_click_1:targetUrl::varchar) OVER (
PARTITION BY page_view_id
ORDER BY derived_tstamp DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
AS first_link_target
FROM
{{.scratch_schema}}.events_staged{{.entropy}}
WHERE page_view_id IS NOT NULL
AND event_name = 'link_click'
)
SELECT
pv.page_view_id,
pv.start_tstamp,
COALESCE(lc.link_clicks, 0) AS link_clicks,
lc.first_link_target,
CASE
WHEN pv.engaged_time_in_s = 0 THEN TRUE
ELSE FALSE
END AS bounced_page_view,
CASE
WHEN pv.engaged_time_in_s > 600 THEN (vertical_percentage_scrolled / 100) * 0.3 + 0.7
ELSE (vertical_percentage_scrolled / 100) * 0.3 + (engaged_time_in_s / 600) * 0.7
END AS engagement_score,
CASE
WHEN pv.refr_medium = 'search'
AND RLIKE(LOWER(pv.mkt_medium), '.*(cpc|ppc|sem|paidsearch).*')
OR RLIKE(LOWER(pv.mkt_source), '.*(cpc|ppc|sem|paidsearch).*') THEN 'paidsearch'
WHEN ILIKE(pv.mkt_medium, '%paidsearch%')
OR ILIKE(pv.mkt_source, '%paidsearch%') THEN 'paidsearch'
WHEN RLIKE(LOWER(mkt_source), '.*(adwords|google_paid|googleads).*')
OR RLIKE(LOWER(mkt_medium), '.*(adwords|google_paid|googleads).*') THEN 'paidsearch'
WHEN ILIKE(pv.mkt_source, '%google%')
AND ILIKE(pv.mkt_medium, '%ads%') THEN 'paidsearch'
WHEN pv.refr_urlhost IN ('www.googleadservices.com','googleads.g.doubleclick.net') THEN 'paidsearch'
WHEN RLIKE(LOWER(pv.mkt_medium), '.*(cpv|cpa|cpp|content-text|advertising|ads).*') THEN 'advertising'
WHEN RLIKE(LOWER(pv.mkt_medium), '.*(display|cpm|banner).*') THEN 'display'
WHEN pv.refr_medium IS NULL
AND NOT ILIKE(pv.page_url, '%utm_%') THEN 'direct'
WHEN (LOWER(pv.refr_medium) = 'search' AND pv.mkt_medium IS NULL)
OR (LOWER(pv.refr_medium) = 'search' AND LOWER(pv.mkt_medium) = 'organic') THEN 'organicsearch'
WHEN pv.refr_medium = 'social'
OR RLIKE(LOWER(pv.mkt_source), '^((.*(facebook|linkedin|instagram|insta|slideshare|social|tweet|twitter|youtube|lnkd|pinterest|googleplus|instagram|plus.google.com|quora|reddit|t.co|twitch|viadeo|xing|youtube).*)|(yt|fb|li))$')
OR RLIKE(LOWER(pv.mkt_medium), '^.*(social|facebook|linkedin|twitter|instagram|tweet).*$') THEN 'social'
WHEN pv.refr_medium = 'email'
OR ILIKE(pv.mkt_medium, '_mail') THEN 'email'
WHEN ILIKE(pv.mkt_medium, 'affiliate') THEN 'affiliate'
WHEN pv.refr_medium = 'unknown'
OR ILIKE(pv.mkt_medium, 'referral')
OR ILIKE(pv.mkt_medium, 'referal') THEN 'referral'
WHEN pv.refr_medium = 'internal' THEN 'internal'
ELSE 'others'
END AS channel
FROM
{{.scratch_schema}}.page_views_staged{{.entropy}} AS pv
LEFT JOIN (SELECT * FROM link_clicks QUALIFY ROW_NUMBER() OVER (PARTITION BY page_view_id ORDER BY page_view_id) = 1) AS lc
ON lc.page_view_id = pv.page_view_id
);
|
#建表
#表语句插入
# c_application
CREATE TABLE `c_application` (
`id` bigint(20) NOT NULL COMMENT 'ID',
`app_id` varchar(64) DEFAULT NULL COMMENT '开发者ID,提供给各个应用的设别码',
`app_secret` varchar(64) DEFAULT NULL COMMENT '开发者密码是校验开发者身份的密码,具有极高的安全性',
`index_url` varchar(255) DEFAULT NULL COMMENT '首页访问地址',
`name_` varchar(20) DEFAULT NULL COMMENT '应用名称',
`logo_url` varchar(200) DEFAULT NULL COMMENT '应用logo',
`desc_` varchar(200) DEFAULT NULL COMMENT '功能描述',
`code_` varchar(100) DEFAULT NULL COMMENT '应用编码',
`order_no` int(11) DEFAULT NULL COMMENT '序号',
`app_type` smallint(6) DEFAULT NULL COMMENT '应用/服务类型: 1 应用 2服务 3既是应用也是服务',
`type_` varchar(100) DEFAULT NULL COMMENT '应用/服务分类(共性应用、统一平台、共性服务、共性模块等等)',
`provider_` varchar(8) DEFAULT NULL COMMENT '提供方 pt 平台 zk 中科 等等',
`status_` bit(1) DEFAULT NULL COMMENT '是否启用',
`random_str` varchar(36) DEFAULT NULL COMMENT '随机序列',
`create_user` bigint(20) DEFAULT NULL COMMENT '创建人id',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_user` bigint(20) DEFAULT NULL COMMENT '更新人id',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`org_id` varchar(64) DEFAULT NULL COMMENT '应用所属单位Id',
`org_system_code` varchar(64) DEFAULT NULL COMMENT '单位所属体系编码',
`org_name` varchar(164) DEFAULT NULL COMMENT '单位名称',
`reduce_time` double NOT NULL DEFAULT '0' COMMENT '使用此应用,可以节省多少工期(人/天)',
`reduce_cost` int(11) NOT NULL DEFAULT '0' COMMENT '使用此应用,可以节省多少前(元)',
`original_time` double NOT NULL DEFAULT '0' COMMENT '此应用程序的初始预计工期(人/天)',
`original_cost` int(11) NOT NULL DEFAULT '0' COMMENT '此应用程序的初始预计成本(人(元)',
`is_fast_app` char(1) DEFAULT 'N' COMMENT '是否快速应用开发',
`biz_config_id` bigint(20) DEFAULT NULL COMMENT '配置表关联ID',
`hots_count` int(11) DEFAULT '0' COMMENT '热门程度',
`reduce_build_cost` int(11) NOT NULL DEFAULT '0' COMMENT '使用此应用,可以节省多少建设成本(元)',
`reduce_use_cost` int(11) NOT NULL DEFAULT '0' COMMENT '使用此应用,可以节省多少使用成本(元)',
`reduce_protect_cost` int(11) NOT NULL DEFAULT '0' COMMENT '使用此应用,可以节省多少维护成本(元)',
`public_is` bit(1) NOT NULL DEFAULT b'0' COMMENT '应用是否公有的 true表示公有,谁都可以访问,至于应用内部的资源,应用程序自己决定,要想有公有的菜单,完全可以在前端写死',
`service_id` varchar(100) DEFAULT NULL COMMENT '服务注册中心的唯一标示: 比如eurake中的serviceId',
`full_root_path` varchar(200) DEFAULT NULL COMMENT '应用程序的完整根路径',
PRIMARY KEY (`id`),
UNIQUE KEY `app_id_unique` (`app_id`) USING BTREE COMMENT 'appId必须唯一'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='应用';
#f_file_usernum
CREATE TABLE `f_file_usernum` (
`id` bigint(20) NOT NULL,
`app_id` varchar(64) DEFAULT NULL COMMENT '应用id',
`type` varchar(255) DEFAULT 'pan' COMMENT '文件类型 云盘数据:pan 接口数据:api',
`data_type` varchar(255) DEFAULT NULL COMMENT '数据类型 image/video/audio/doc/other/DIR',
`num` varchar(255) DEFAULT NULL COMMENT '数量',
`fyear_month` varchar(50) DEFAULT NULL COMMENT '年月',
`create_time` datetime DEFAULT NULL,
`create_user` bigint(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='文件文件数量表';
#地区导入表
CREATE TABLE `b_area` (
`id` bigint(11) NOT NULL,
`name` varchar(255) DEFAULT NULL COMMENT '名称',
`code` varchar(64) CHARACTER SET utf8 DEFAULT NULL COMMENT '地区编码',
`full_name` varchar(255) DEFAULT NULL COMMENT '全名',
`order_num` int(11) DEFAULT NULL COMMENT '排序',
`parent_id` bigint(11) DEFAULT NULL COMMENT '父id',
`tree_path` varchar(255) DEFAULT NULL COMMENT '路径',
`longitude` varchar(255) DEFAULT NULL COMMENT '经度',
`latitude` varchar(255) DEFAULT NULL COMMENT '维度',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`create_user` bigint(11) DEFAULT NULL COMMENT '创建人',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`update_user` bigint(11) DEFAULT NULL COMMENT '更新人',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='地区表'; |
-- phpMyAdmin SQL Dump
-- version 4.8.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: 15-Jan-2019 às 14:34
-- Versão do servidor: 10.1.37-MariaDB
-- versão do PHP: 7.2.12
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: `empresa`
--
-- --------------------------------------------------------
--
-- Estrutura da tabela `aluguel`
--
CREATE TABLE `aluguel` (
`ID_ALUGUEL` int(11) NOT NULL,
`COD_REFERENCIA` varchar(20) DEFAULT NULL,
`IDCLIENTE` int(11) DEFAULT NULL,
`DT_ALUGUEL` date DEFAULT NULL,
`DT_DEVOLUCAO` date DEFAULT NULL,
`ID_STATUS` int(11) DEFAULT NULL,
`VALOR_TOTAL` decimal(13,2) DEFAULT NULL,
`DADOS_ADICIONAIS` varchar(50) DEFAULT NULL,
`IDFUNCIONARIO` int(11) DEFAULT NULL,
`COMISSAO` decimal(13,2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `aluguel`
--
INSERT INTO `aluguel` (`ID_ALUGUEL`, `COD_REFERENCIA`, `IDCLIENTE`, `DT_ALUGUEL`, `DT_DEVOLUCAO`, `ID_STATUS`, `VALOR_TOTAL`, `DADOS_ADICIONAIS`, `IDFUNCIONARIO`, `COMISSAO`) VALUES
(22, '', 84, '2019-01-15', '2019-01-16', NULL, '0.00', '', NULL, '0.00'),
(23, '', 84, '2019-01-17', '2019-01-18', NULL, '0.00', '', NULL, '0.00');
-- --------------------------------------------------------
--
-- Estrutura da tabela `caixa`
--
CREATE TABLE `caixa` (
`IDCAIXA` int(11) NOT NULL,
`IDCLIENTE` varchar(11) DEFAULT NULL,
`VALOR` decimal(13,2) DEFAULT NULL,
`IDTIPOMOVI` int(11) DEFAULT NULL,
`DESCRICAO` varchar(50) DEFAULT NULL,
`DUPLICATA` varchar(50) DEFAULT NULL,
`DATAVAL` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `caixa`
--
INSERT INTO `caixa` (`IDCAIXA`, `IDCLIENTE`, `VALOR`, `IDTIPOMOVI`, `DESCRICAO`, `DUPLICATA`, `DATAVAL`) VALUES
(2, '2', '10.00', 2, 'Lançamento efetuado com sucesso!', 'Duplicata-2', '2019-01-14'),
(3, '84', '50.00', 1, 'Lançamento efetuado com sucesso!', '21-1', '2019-01-14');
-- --------------------------------------------------------
--
-- Estrutura da tabela `cliente`
--
CREATE TABLE `cliente` (
`IDCLIENTE` int(11) NOT NULL,
`NOME` varchar(100) NOT NULL,
`CPF_CNPJ` varchar(25) DEFAULT NULL,
`ENDERECO` varchar(100) DEFAULT NULL,
`NUMERO` smallint(6) DEFAULT NULL,
`COMPLEMENTO` varchar(100) DEFAULT NULL,
`BAIRRO` varchar(100) DEFAULT NULL,
`CIDADE` varchar(100) DEFAULT NULL,
`UF` varchar(2) DEFAULT NULL,
`CEP` varchar(15) DEFAULT NULL,
`TELEFONE` varchar(20) DEFAULT NULL,
`CELULAR` varchar(20) DEFAULT NULL,
`EMAIL` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `cliente`
--
INSERT INTO `cliente` (`IDCLIENTE`, `NOME`, `CPF_CNPJ`, `ENDERECO`, `NUMERO`, `COMPLEMENTO`, `BAIRRO`, `CIDADE`, `UF`, `CEP`, `TELEFONE`, `CELULAR`, `EMAIL`) VALUES
(84, 'Matheus', '123.444.444-44', 'tesdte', 0, '', '', '', '', '', '', '', 'matheusmoreira3693@gmail.com');
-- --------------------------------------------------------
--
-- Estrutura da tabela `config`
--
CREATE TABLE `config` (
`IDCONFIG` int(11) NOT NULL,
`EMAIL` varchar(100) DEFAULT NULL,
`SENHA` varchar(100) DEFAULT NULL,
`PORTA` varchar(10) DEFAULT NULL,
`HOST` varchar(100) DEFAULT NULL,
`TLS` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `config`
--
INSERT INTO `config` (`IDCONFIG`, `EMAIL`, `SENHA`, `PORTA`, `HOST`, `TLS`) VALUES
(1, 'matheusmoreira3693@gmail.com', 'Biruta@147sa', '465', 'smtp.gmail.com', 1);
-- --------------------------------------------------------
--
-- Estrutura da tabela `contador`
--
CREATE TABLE `contador` (
`IDCONTADOR` int(11) NOT NULL,
`CONTADOR` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `contador`
--
INSERT INTO `contador` (`IDCONTADOR`, `CONTADOR`) VALUES
(1, '35');
-- --------------------------------------------------------
--
-- Estrutura da tabela `contadorpagar`
--
CREATE TABLE `contadorpagar` (
`IDCONTADOR` int(11) NOT NULL,
`CONTADOR` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `contadorpagar`
--
INSERT INTO `contadorpagar` (`IDCONTADOR`, `CONTADOR`) VALUES
(1, '2');
-- --------------------------------------------------------
--
-- Estrutura da tabela `cor`
--
CREATE TABLE `cor` (
`IDCOR` int(11) NOT NULL,
`NOMECOR` varchar(50) DEFAULT NULL,
`DECRICAO` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estrutura da tabela `duplicatas`
--
CREATE TABLE `duplicatas` (
`IDDUPLICATA` int(11) NOT NULL,
`IDCLIENTE` int(11) DEFAULT NULL,
`IDALUGUEL` int(11) DEFAULT NULL,
`IDTIPOMOVIMENTACAO` int(11) DEFAULT NULL,
`IDFORMAPAGAMENTO` int(11) DEFAULT NULL,
`NUMEROPARCELA` varchar(30) DEFAULT NULL,
`VALORDUPLICATA` decimal(13,2) DEFAULT NULL,
`VENCIMENTO` date DEFAULT NULL,
`DESCRICAO` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estrutura da tabela `duplicatas_pagar`
--
CREATE TABLE `duplicatas_pagar` (
`IDDUPLICATASPAGAR` int(11) NOT NULL,
`NUMERODUPLICATA` varchar(20) DEFAULT NULL,
`IDFORNECEDOR` int(11) DEFAULT NULL,
`VENCIMENTO` date DEFAULT NULL,
`IDFORMAPAGAMENTO` int(11) DEFAULT NULL,
`DATAPAGAMENTO` date DEFAULT NULL,
`VALORTOTAL` decimal(13,2) DEFAULT NULL,
`VALORPAGO` decimal(13,2) DEFAULT NULL,
`VALORRESTANTE` decimal(13,2) DEFAULT NULL,
`DESCRICAO` varchar(40) DEFAULT NULL,
`IDALUGUEL` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `duplicatas_pagar`
--
INSERT INTO `duplicatas_pagar` (`IDDUPLICATASPAGAR`, `NUMERODUPLICATA`, `IDFORNECEDOR`, `VENCIMENTO`, `IDFORMAPAGAMENTO`, `DATAPAGAMENTO`, `VALORTOTAL`, `VALORPAGO`, `VALORRESTANTE`, `DESCRICAO`, `IDALUGUEL`) VALUES
(2, 'Duplicata-2', 2, '2019-01-14', 1, '2019-01-14', '10.00', '10.00', '0.00', '', NULL);
-- --------------------------------------------------------
--
-- Estrutura da tabela `duplicatas_receber`
--
CREATE TABLE `duplicatas_receber` (
`IDDUPLICATASRECEBER` int(11) NOT NULL,
`NUMERODUPLICATA` varchar(20) DEFAULT NULL,
`IDCLIENTE` int(11) DEFAULT NULL,
`VENCIMENTO` date DEFAULT NULL,
`IDFORMAPAGAMENTO` int(11) DEFAULT NULL,
`DATAPAGAMENTO` date DEFAULT NULL,
`VALORTOTAL` decimal(13,2) DEFAULT NULL,
`VALORPAGO` decimal(13,2) DEFAULT NULL,
`VALORRESTANTE` decimal(13,2) DEFAULT NULL,
`DESCRICAO` varchar(40) DEFAULT NULL,
`IDALUGUEL` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estrutura da tabela `email`
--
CREATE TABLE `email` (
`IDEMAIL` int(11) NOT NULL,
`IDCLIENTE` int(11) DEFAULT NULL,
`ASSUNTO` varchar(30) DEFAULT NULL,
`DESCRICAO` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `email`
--
INSERT INTO `email` (`IDEMAIL`, `IDCLIENTE`, `ASSUNTO`, `DESCRICAO`) VALUES
(1, 84, 'tes', 'teste'),
(2, 84, 'yrd', 'yrdyr'),
(3, 84, 'tste', 'teste');
-- --------------------------------------------------------
--
-- Estrutura da tabela `empresa`
--
CREATE TABLE `empresa` (
`IDEMPRESA` int(11) NOT NULL,
`NOMECLIENTE` varchar(100) DEFAULT NULL,
`ENDERECO` varchar(100) DEFAULT NULL,
`BAIRRO` varchar(100) DEFAULT NULL,
`CEP` varchar(10) DEFAULT NULL,
`CIDADE` varchar(100) DEFAULT NULL,
`UF` varchar(2) DEFAULT NULL,
`TELEFONE` varchar(50) DEFAULT NULL,
`FAX` varchar(50) DEFAULT NULL,
`CNPJCPF` varchar(20) DEFAULT NULL,
`IE` varchar(20) DEFAULT NULL,
`EMAIL` varchar(50) DEFAULT NULL,
`REGISTRO` varchar(20) DEFAULT NULL,
`NUMERO` varchar(20) DEFAULT NULL,
`COMPLEMENTO` varchar(50) DEFAULT NULL,
`NOMEFANTASIA` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `empresa`
--
INSERT INTO `empresa` (`IDEMPRESA`, `NOMECLIENTE`, `ENDERECO`, `BAIRRO`, `CEP`, `CIDADE`, `UF`, `TELEFONE`, `FAX`, `CNPJCPF`, `IE`, `EMAIL`, `REGISTRO`, `NUMERO`, `COMPLEMENTO`, `NOMEFANTASIA`) VALUES
(1, 'BMS LTDA', 'Avenida alguma coisa', 'Fatima', '36570-000', 'Viçosa', 'MG', '38919414', '123', '03054436000151', '12345678', 'email@grupobms.com.r', '123', '45', 'Casa', 'BMS LTDA');
-- --------------------------------------------------------
--
-- Estrutura da tabela `estoquepecas`
--
CREATE TABLE `estoquepecas` (
`IDESTOQUE` int(11) NOT NULL,
`IDPRODUTO` int(11) DEFAULT NULL,
`QUANTIDADE` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `estoquepecas`
--
INSERT INTO `estoquepecas` (`IDESTOQUE`, `IDPRODUTO`, `QUANTIDADE`) VALUES
(28, 44, 2);
-- --------------------------------------------------------
--
-- Estrutura da tabela `forma_pagamento`
--
CREATE TABLE `forma_pagamento` (
`IDFORMA_PAGAMENTO` int(11) NOT NULL,
`FORMA_DE_PAGAMENTO` varchar(30) DEFAULT NULL,
`DESCRICAO` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `forma_pagamento`
--
INSERT INTO `forma_pagamento` (`IDFORMA_PAGAMENTO`, `FORMA_DE_PAGAMENTO`, `DESCRICAO`) VALUES
(1, 'DINHEIRO', 'PAGAMENTO EM DINHEIRO'),
(2, 'Cartão de crédito', 'Pagamento em cartão de crédito');
-- --------------------------------------------------------
--
-- Estrutura da tabela `fornecedor`
--
CREATE TABLE `fornecedor` (
`IDFORNECEDOR` int(11) NOT NULL,
`NOMEFANTASIA` varchar(100) DEFAULT NULL,
`RAZAOSOCIAL` varchar(100) DEFAULT NULL,
`CNPJ_CPF` varchar(30) DEFAULT NULL,
`IE` varchar(20) DEFAULT NULL,
`ENDERECO` varchar(100) DEFAULT NULL,
`NUMERO` varchar(10) DEFAULT NULL,
`BAIRRO` varchar(50) DEFAULT NULL,
`CIDADE` varchar(50) DEFAULT NULL,
`UF` varchar(2) DEFAULT NULL,
`EMAIL` varchar(100) DEFAULT NULL,
`TELEFONE` varchar(15) DEFAULT NULL,
`CELULAR` varchar(15) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `fornecedor`
--
INSERT INTO `fornecedor` (`IDFORNECEDOR`, `NOMEFANTASIA`, `RAZAOSOCIAL`, `CNPJ_CPF`, `IE`, `ENDERECO`, `NUMERO`, `BAIRRO`, `CIDADE`, `UF`, `EMAIL`, `TELEFONE`, `CELULAR`) VALUES
(1, '32132131', '321321', '1232132131231', '', '', '', '', '', '', '', '', ''),
(2, 'treste', 'tetse', '12.222.222/2222-22', '', '', '', '', '', '', '', '', '');
-- --------------------------------------------------------
--
-- Estrutura da tabela `fotos`
--
CREATE TABLE `fotos` (
`IDFOTO` int(11) NOT NULL,
`IDPRODUTO` int(11) DEFAULT NULL,
`NOMEFOTO` varchar(30) DEFAULT NULL,
`DESCRICAOFOTOS` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `fotos`
--
INSERT INTO `fotos` (`IDFOTO`, `IDPRODUTO`, `NOMEFOTO`, `DESCRICAOFOTOS`) VALUES
(23, 44, 'img-teste.png', '');
-- --------------------------------------------------------
--
-- Estrutura da tabela `funcionario`
--
CREATE TABLE `funcionario` (
`IDFUNCIONARIO` int(11) NOT NULL,
`NOMEFUNCIONARIO` varchar(100) NOT NULL,
`CPF` varchar(25) DEFAULT NULL,
`RG` varchar(30) DEFAULT NULL,
`COMISSAO` int(11) DEFAULT NULL,
`ENDERECO` varchar(100) DEFAULT NULL,
`NUMERO` varchar(10) DEFAULT NULL,
`BAIRRO` varchar(100) DEFAULT NULL,
`CIDADE` varchar(100) DEFAULT NULL,
`UF` varchar(5) DEFAULT NULL,
`EMAIL` varchar(100) DEFAULT NULL,
`TELEFONE` varchar(15) DEFAULT NULL,
`CELULAR` varchar(15) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `funcionario`
--
INSERT INTO `funcionario` (`IDFUNCIONARIO`, `NOMEFUNCIONARIO`, `CPF`, `RG`, `COMISSAO`, `ENDERECO`, `NUMERO`, `BAIRRO`, `CIDADE`, `UF`, `EMAIL`, `TELEFONE`, `CELULAR`) VALUES
(1, 'tetse', '', '', 0, '', '', '', '', '', '', '', '');
-- --------------------------------------------------------
--
-- Estrutura da tabela `modelo`
--
CREATE TABLE `modelo` (
`IDMODELO` int(11) NOT NULL,
`NOMEMODELO` varchar(100) NOT NULL,
`TAMANHOMODELO` varchar(5) DEFAULT NULL,
`NUMERO` tinyint(4) DEFAULT NULL,
`DESCRICAOMODELO` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `modelo`
--
INSERT INTO `modelo` (`IDMODELO`, `NOMEMODELO`, `TAMANHOMODELO`, `NUMERO`, `DESCRICAOMODELO`) VALUES
(1, 'teste', 'M|', 55, 'teste');
-- --------------------------------------------------------
--
-- Estrutura da tabela `movimentacaoestoque`
--
CREATE TABLE `movimentacaoestoque` (
`IDMOVIESTOQUE` int(11) NOT NULL,
`IDPRODUTO` int(11) DEFAULT NULL,
`QUANTIDADEALUGADA` int(11) DEFAULT NULL,
`IDSTATUS_MOVIMENTACAO` int(11) DEFAULT NULL,
`ID_PRODUTOS_ALUGUEL` int(11) NOT NULL,
`BAIXA` varchar(3) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `movimentacaoestoque`
--
INSERT INTO `movimentacaoestoque` (`IDMOVIESTOQUE`, `IDPRODUTO`, `QUANTIDADEALUGADA`, `IDSTATUS_MOVIMENTACAO`, `ID_PRODUTOS_ALUGUEL`, `BAIXA`) VALUES
(46, 44, 10, 1, 53, NULL);
-- --------------------------------------------------------
--
-- Estrutura da tabela `produtos`
--
CREATE TABLE `produtos` (
`IDPRODUTO` int(11) NOT NULL,
`NOME` varchar(100) NOT NULL,
`VALORVENDA` decimal(13,2) DEFAULT NULL,
`VALORALUGUEL` decimal(13,2) DEFAULT NULL,
`UNIDADE` varchar(10) DEFAULT NULL,
`DESCRICAOPRODUTO` varchar(100) DEFAULT NULL,
`COD_BARRAS` varchar(100) DEFAULT NULL,
`COD_REFERENCIA` varchar(100) DEFAULT NULL,
`IDCOR` int(11) DEFAULT NULL,
`IDMODELO` int(11) DEFAULT NULL,
`IDTAMANHO` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `produtos`
--
INSERT INTO `produtos` (`IDPRODUTO`, `NOME`, `VALORVENDA`, `VALORALUGUEL`, `UNIDADE`, `DESCRICAOPRODUTO`, `COD_BARRAS`, `COD_REFERENCIA`, `IDCOR`, `IDMODELO`, `IDTAMANHO`) VALUES
(44, 'Produto teste', '10.00', '12.00', 'UN', 'tetste', '1234', '1234', NULL, 1, 5),
(45, 'produto TESTE', '123.00', '123.00', '', '', '', '', NULL, NULL, NULL);
-- --------------------------------------------------------
--
-- Estrutura da tabela `produtos_aluguel`
--
CREATE TABLE `produtos_aluguel` (
`IDPRODUTO_ALUGUEL` int(11) NOT NULL,
`ID_ALUGUEL` int(11) DEFAULT NULL,
`IDPRODUTO` int(11) DEFAULT NULL,
`QUANTIDADE` int(11) DEFAULT NULL,
`VALORTOTAL` decimal(13,2) DEFAULT NULL,
`DESCONTO` decimal(13,2) DEFAULT NULL,
`DADOSADICIONAIS` varchar(50) DEFAULT NULL,
`BAIXA` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `produtos_aluguel`
--
INSERT INTO `produtos_aluguel` (`IDPRODUTO_ALUGUEL`, `ID_ALUGUEL`, `IDPRODUTO`, `QUANTIDADE`, `VALORTOTAL`, `DESCONTO`, `DADOSADICIONAIS`, `BAIXA`) VALUES
(54, 22, 44, 1, '10.00', NULL, '', 'NAO'),
(55, 23, 44, 1, '10.00', NULL, '', 'NAO');
-- --------------------------------------------------------
--
-- Estrutura da tabela `produtos_traje`
--
CREATE TABLE `produtos_traje` (
`IDPRODUTOS_TRAJE` int(11) NOT NULL,
`IDPRODUTO` int(11) DEFAULT NULL,
`IDTRAJE` int(11) DEFAULT NULL,
`QUANTIDADE` int(11) DEFAULT NULL,
`DESCRICAO` varchar(50) DEFAULT NULL,
`VALOR` decimal(13,2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estrutura da tabela `status_aluguel`
--
CREATE TABLE `status_aluguel` (
`ID_STATUS` int(11) NOT NULL,
`NOME_STATUS` varchar(25) DEFAULT NULL,
`DESCRICAO_ALUGUEL` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `status_aluguel`
--
INSERT INTO `status_aluguel` (`ID_STATUS`, `NOME_STATUS`, `DESCRICAO_ALUGUEL`) VALUES
(1, 'ALUGADO', 'Produto alugado'),
(2, 'FECHADO', 'Aluguel Fechado'),
(3, 'ESPERA', 'Em espera');
-- --------------------------------------------------------
--
-- Estrutura da tabela `status_movimentacao`
--
CREATE TABLE `status_movimentacao` (
`IDSTATUS_MOVIMENTACAO` int(11) NOT NULL,
`NOME_STATUS_MOVIMENTACAO` varchar(50) DEFAULT NULL,
`DESCRICAO_STATUS_MOVIMENTACAO` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `status_movimentacao`
--
INSERT INTO `status_movimentacao` (`IDSTATUS_MOVIMENTACAO`, `NOME_STATUS_MOVIMENTACAO`, `DESCRICAO_STATUS_MOVIMENTACAO`) VALUES
(1, 'Aluguel', 'Movimentacao de Aluguel'),
(2, 'Venda', 'Movimentacao de Venda');
-- --------------------------------------------------------
--
-- Estrutura da tabela `tamanho`
--
CREATE TABLE `tamanho` (
`IDTAMANHO` int(11) NOT NULL,
`NOMETAMANHO` varchar(50) DEFAULT NULL,
`DESCRICAO` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `tamanho`
--
INSERT INTO `tamanho` (`IDTAMANHO`, `NOMETAMANHO`, `DESCRICAO`) VALUES
(5, 'M', 'tamanho m');
-- --------------------------------------------------------
--
-- Estrutura da tabela `tipomovimentacao`
--
CREATE TABLE `tipomovimentacao` (
`IDTIPOMOVIMENTACAO` int(11) NOT NULL,
`NOMETIPO` varchar(30) DEFAULT NULL,
`DESCRICAO` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `tipomovimentacao`
--
INSERT INTO `tipomovimentacao` (`IDTIPOMOVIMENTACAO`, `NOMETIPO`, `DESCRICAO`) VALUES
(1, 'CREDITO', 'Entrada no caixa'),
(2, 'DEBITO', 'DEITO DE VALOR NO CAIXA');
-- --------------------------------------------------------
--
-- Estrutura da tabela `traje`
--
CREATE TABLE `traje` (
`IDTRAJE` int(11) NOT NULL,
`NOMETRAJE` varchar(50) DEFAULT NULL,
`VALOR` decimal(13,2) DEFAULT NULL,
`DESCRICAO` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `traje`
--
INSERT INTO `traje` (`IDTRAJE`, `NOMETRAJE`, `VALOR`, `DESCRICAO`) VALUES
(2, 'Traje teste', '100.00', 'descrição');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `aluguel`
--
ALTER TABLE `aluguel`
ADD PRIMARY KEY (`ID_ALUGUEL`),
ADD KEY `IDCLIENTE` (`IDCLIENTE`),
ADD KEY `ID_STATUS` (`ID_STATUS`),
ADD KEY `IDFUNCIONARIO` (`IDFUNCIONARIO`);
--
-- Indexes for table `caixa`
--
ALTER TABLE `caixa`
ADD PRIMARY KEY (`IDCAIXA`),
ADD KEY `IDCLIENTE` (`IDCLIENTE`),
ADD KEY `IDTIPOMOVI` (`IDTIPOMOVI`);
--
-- Indexes for table `cliente`
--
ALTER TABLE `cliente`
ADD PRIMARY KEY (`IDCLIENTE`);
--
-- Indexes for table `config`
--
ALTER TABLE `config`
ADD PRIMARY KEY (`IDCONFIG`);
--
-- Indexes for table `contador`
--
ALTER TABLE `contador`
ADD PRIMARY KEY (`IDCONTADOR`);
--
-- Indexes for table `contadorpagar`
--
ALTER TABLE `contadorpagar`
ADD PRIMARY KEY (`IDCONTADOR`);
--
-- Indexes for table `cor`
--
ALTER TABLE `cor`
ADD PRIMARY KEY (`IDCOR`);
--
-- Indexes for table `duplicatas`
--
ALTER TABLE `duplicatas`
ADD PRIMARY KEY (`IDDUPLICATA`),
ADD KEY `IDCLIENTE` (`IDCLIENTE`),
ADD KEY `IDALUGUEL` (`IDALUGUEL`),
ADD KEY `IDTIPOMOVIMENTACAO` (`IDTIPOMOVIMENTACAO`),
ADD KEY `IDFORMAPAGAMENTO` (`IDFORMAPAGAMENTO`);
--
-- Indexes for table `duplicatas_pagar`
--
ALTER TABLE `duplicatas_pagar`
ADD PRIMARY KEY (`IDDUPLICATASPAGAR`),
ADD UNIQUE KEY `NUMERODUPLICATA` (`NUMERODUPLICATA`),
ADD KEY `IDFORMAPAGAMENTO` (`IDFORMAPAGAMENTO`),
ADD KEY `duplicatas_pagar_ibfk_1` (`IDFORNECEDOR`);
--
-- Indexes for table `duplicatas_receber`
--
ALTER TABLE `duplicatas_receber`
ADD PRIMARY KEY (`IDDUPLICATASRECEBER`),
ADD UNIQUE KEY `NUMERODUPLICATA` (`NUMERODUPLICATA`),
ADD KEY `IDCLIENTE` (`IDCLIENTE`),
ADD KEY `IDFORMAPAGAMENTO` (`IDFORMAPAGAMENTO`);
--
-- Indexes for table `email`
--
ALTER TABLE `email`
ADD PRIMARY KEY (`IDEMAIL`),
ADD KEY `IDCLIENTE` (`IDCLIENTE`);
--
-- Indexes for table `empresa`
--
ALTER TABLE `empresa`
ADD PRIMARY KEY (`IDEMPRESA`);
--
-- Indexes for table `estoquepecas`
--
ALTER TABLE `estoquepecas`
ADD PRIMARY KEY (`IDESTOQUE`),
ADD KEY `IDPRODUTO` (`IDPRODUTO`);
--
-- Indexes for table `forma_pagamento`
--
ALTER TABLE `forma_pagamento`
ADD PRIMARY KEY (`IDFORMA_PAGAMENTO`);
--
-- Indexes for table `fornecedor`
--
ALTER TABLE `fornecedor`
ADD PRIMARY KEY (`IDFORNECEDOR`);
--
-- Indexes for table `fotos`
--
ALTER TABLE `fotos`
ADD PRIMARY KEY (`IDFOTO`),
ADD UNIQUE KEY `NOMEFOTO` (`NOMEFOTO`),
ADD KEY `IDPRODUTO` (`IDPRODUTO`);
--
-- Indexes for table `funcionario`
--
ALTER TABLE `funcionario`
ADD PRIMARY KEY (`IDFUNCIONARIO`);
--
-- Indexes for table `modelo`
--
ALTER TABLE `modelo`
ADD PRIMARY KEY (`IDMODELO`);
--
-- Indexes for table `movimentacaoestoque`
--
ALTER TABLE `movimentacaoestoque`
ADD PRIMARY KEY (`IDMOVIESTOQUE`),
ADD KEY `IDPRODUTO` (`IDPRODUTO`),
ADD KEY `IDSTATUS_MOVIMENTACAO` (`IDSTATUS_MOVIMENTACAO`);
--
-- Indexes for table `produtos`
--
ALTER TABLE `produtos`
ADD PRIMARY KEY (`IDPRODUTO`),
ADD KEY `IDCOR` (`IDCOR`),
ADD KEY `IDMODELO` (`IDMODELO`),
ADD KEY `produtos_ibfk_3` (`IDTAMANHO`);
--
-- Indexes for table `produtos_aluguel`
--
ALTER TABLE `produtos_aluguel`
ADD PRIMARY KEY (`IDPRODUTO_ALUGUEL`),
ADD KEY `IDPRODUTO` (`IDPRODUTO`),
ADD KEY `ID_ALUGUEL` (`ID_ALUGUEL`);
--
-- Indexes for table `produtos_traje`
--
ALTER TABLE `produtos_traje`
ADD PRIMARY KEY (`IDPRODUTOS_TRAJE`),
ADD KEY `IDPRODUTO` (`IDPRODUTO`),
ADD KEY `IDTRAJE` (`IDTRAJE`);
--
-- Indexes for table `status_aluguel`
--
ALTER TABLE `status_aluguel`
ADD PRIMARY KEY (`ID_STATUS`);
--
-- Indexes for table `status_movimentacao`
--
ALTER TABLE `status_movimentacao`
ADD PRIMARY KEY (`IDSTATUS_MOVIMENTACAO`);
--
-- Indexes for table `tamanho`
--
ALTER TABLE `tamanho`
ADD PRIMARY KEY (`IDTAMANHO`);
--
-- Indexes for table `tipomovimentacao`
--
ALTER TABLE `tipomovimentacao`
ADD PRIMARY KEY (`IDTIPOMOVIMENTACAO`);
--
-- Indexes for table `traje`
--
ALTER TABLE `traje`
ADD PRIMARY KEY (`IDTRAJE`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `aluguel`
--
ALTER TABLE `aluguel`
MODIFY `ID_ALUGUEL` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;
--
-- AUTO_INCREMENT for table `caixa`
--
ALTER TABLE `caixa`
MODIFY `IDCAIXA` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `cliente`
--
ALTER TABLE `cliente`
MODIFY `IDCLIENTE` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=85;
--
-- AUTO_INCREMENT for table `config`
--
ALTER TABLE `config`
MODIFY `IDCONFIG` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `contador`
--
ALTER TABLE `contador`
MODIFY `IDCONTADOR` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `contadorpagar`
--
ALTER TABLE `contadorpagar`
MODIFY `IDCONTADOR` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `cor`
--
ALTER TABLE `cor`
MODIFY `IDCOR` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `duplicatas`
--
ALTER TABLE `duplicatas`
MODIFY `IDDUPLICATA` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `duplicatas_pagar`
--
ALTER TABLE `duplicatas_pagar`
MODIFY `IDDUPLICATASPAGAR` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `duplicatas_receber`
--
ALTER TABLE `duplicatas_receber`
MODIFY `IDDUPLICATASRECEBER` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `email`
--
ALTER TABLE `email`
MODIFY `IDEMAIL` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `empresa`
--
ALTER TABLE `empresa`
MODIFY `IDEMPRESA` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `estoquepecas`
--
ALTER TABLE `estoquepecas`
MODIFY `IDESTOQUE` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=29;
--
-- AUTO_INCREMENT for table `forma_pagamento`
--
ALTER TABLE `forma_pagamento`
MODIFY `IDFORMA_PAGAMENTO` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `fornecedor`
--
ALTER TABLE `fornecedor`
MODIFY `IDFORNECEDOR` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `fotos`
--
ALTER TABLE `fotos`
MODIFY `IDFOTO` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;
--
-- AUTO_INCREMENT for table `funcionario`
--
ALTER TABLE `funcionario`
MODIFY `IDFUNCIONARIO` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `modelo`
--
ALTER TABLE `modelo`
MODIFY `IDMODELO` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `movimentacaoestoque`
--
ALTER TABLE `movimentacaoestoque`
MODIFY `IDMOVIESTOQUE` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=47;
--
-- AUTO_INCREMENT for table `produtos`
--
ALTER TABLE `produtos`
MODIFY `IDPRODUTO` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=46;
--
-- AUTO_INCREMENT for table `produtos_aluguel`
--
ALTER TABLE `produtos_aluguel`
MODIFY `IDPRODUTO_ALUGUEL` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=56;
--
-- AUTO_INCREMENT for table `produtos_traje`
--
ALTER TABLE `produtos_traje`
MODIFY `IDPRODUTOS_TRAJE` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `status_aluguel`
--
ALTER TABLE `status_aluguel`
MODIFY `ID_STATUS` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `status_movimentacao`
--
ALTER TABLE `status_movimentacao`
MODIFY `IDSTATUS_MOVIMENTACAO` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `tamanho`
--
ALTER TABLE `tamanho`
MODIFY `IDTAMANHO` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `tipomovimentacao`
--
ALTER TABLE `tipomovimentacao`
MODIFY `IDTIPOMOVIMENTACAO` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `traje`
--
ALTER TABLE `traje`
MODIFY `IDTRAJE` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- Constraints for dumped tables
--
--
-- Limitadores para a tabela `aluguel`
--
ALTER TABLE `aluguel`
ADD CONSTRAINT `aluguel_ibfk_1` FOREIGN KEY (`IDCLIENTE`) REFERENCES `cliente` (`IDCLIENTE`),
ADD CONSTRAINT `aluguel_ibfk_2` FOREIGN KEY (`ID_STATUS`) REFERENCES `status_aluguel` (`ID_STATUS`),
ADD CONSTRAINT `aluguel_ibfk_3` FOREIGN KEY (`IDFUNCIONARIO`) REFERENCES `funcionario` (`IDFUNCIONARIO`);
--
-- Limitadores para a tabela `caixa`
--
ALTER TABLE `caixa`
ADD CONSTRAINT `caixa_ibfk_2` FOREIGN KEY (`IDTIPOMOVI`) REFERENCES `tipomovimentacao` (`IDTIPOMOVIMENTACAO`);
--
-- Limitadores para a tabela `duplicatas`
--
ALTER TABLE `duplicatas`
ADD CONSTRAINT `duplicatas_ibfk_1` FOREIGN KEY (`IDCLIENTE`) REFERENCES `cliente` (`IDCLIENTE`),
ADD CONSTRAINT `duplicatas_ibfk_2` FOREIGN KEY (`IDALUGUEL`) REFERENCES `aluguel` (`ID_ALUGUEL`),
ADD CONSTRAINT `duplicatas_ibfk_3` FOREIGN KEY (`IDTIPOMOVIMENTACAO`) REFERENCES `tipomovimentacao` (`IDTIPOMOVIMENTACAO`),
ADD CONSTRAINT `duplicatas_ibfk_4` FOREIGN KEY (`IDFORMAPAGAMENTO`) REFERENCES `forma_pagamento` (`IDFORMA_PAGAMENTO`);
--
-- Limitadores para a tabela `duplicatas_pagar`
--
ALTER TABLE `duplicatas_pagar`
ADD CONSTRAINT `duplicatas_pagar_ibfk_1` FOREIGN KEY (`IDFORNECEDOR`) REFERENCES `fornecedor` (`IDFORNECEDOR`),
ADD CONSTRAINT `duplicatas_pagar_ibfk_2` FOREIGN KEY (`IDFORMAPAGAMENTO`) REFERENCES `forma_pagamento` (`IDFORMA_PAGAMENTO`);
--
-- Limitadores para a tabela `duplicatas_receber`
--
ALTER TABLE `duplicatas_receber`
ADD CONSTRAINT `duplicatas_receber_ibfk_1` FOREIGN KEY (`IDCLIENTE`) REFERENCES `cliente` (`IDCLIENTE`),
ADD CONSTRAINT `duplicatas_receber_ibfk_2` FOREIGN KEY (`IDFORMAPAGAMENTO`) REFERENCES `forma_pagamento` (`IDFORMA_PAGAMENTO`);
--
-- Limitadores para a tabela `email`
--
ALTER TABLE `email`
ADD CONSTRAINT `email_ibfk_1` FOREIGN KEY (`IDCLIENTE`) REFERENCES `cliente` (`IDCLIENTE`);
--
-- Limitadores para a tabela `estoquepecas`
--
ALTER TABLE `estoquepecas`
ADD CONSTRAINT `estoquepecas_ibfk_1` FOREIGN KEY (`IDPRODUTO`) REFERENCES `produtos` (`IDPRODUTO`);
--
-- Limitadores para a tabela `fotos`
--
ALTER TABLE `fotos`
ADD CONSTRAINT `fotos_ibfk_1` FOREIGN KEY (`IDPRODUTO`) REFERENCES `produtos` (`IDPRODUTO`);
--
-- Limitadores para a tabela `movimentacaoestoque`
--
ALTER TABLE `movimentacaoestoque`
ADD CONSTRAINT `movimentacaoestoque_ibfk_1` FOREIGN KEY (`IDPRODUTO`) REFERENCES `produtos` (`IDPRODUTO`),
ADD CONSTRAINT `movimentacaoestoque_ibfk_2` FOREIGN KEY (`IDSTATUS_MOVIMENTACAO`) REFERENCES `status_movimentacao` (`IDSTATUS_MOVIMENTACAO`);
--
-- Limitadores para a tabela `produtos`
--
ALTER TABLE `produtos`
ADD CONSTRAINT `produtos_ibfk_1` FOREIGN KEY (`IDCOR`) REFERENCES `cor` (`IDCOR`),
ADD CONSTRAINT `produtos_ibfk_2` FOREIGN KEY (`IDMODELO`) REFERENCES `modelo` (`IDMODELO`),
ADD CONSTRAINT `produtos_ibfk_3` FOREIGN KEY (`IDTAMANHO`) REFERENCES `tamanho` (`IDTAMANHO`);
--
-- Limitadores para a tabela `produtos_aluguel`
--
ALTER TABLE `produtos_aluguel`
ADD CONSTRAINT `produtos_aluguel_ibfk_1` FOREIGN KEY (`IDPRODUTO`) REFERENCES `produtos` (`IDPRODUTO`),
ADD CONSTRAINT `produtos_aluguel_ibfk_2` FOREIGN KEY (`ID_ALUGUEL`) REFERENCES `aluguel` (`ID_ALUGUEL`);
--
-- Limitadores para a tabela `produtos_traje`
--
ALTER TABLE `produtos_traje`
ADD CONSTRAINT `produtos_traje_ibfk_1` FOREIGN KEY (`IDPRODUTO`) REFERENCES `produtos` (`IDPRODUTO`),
ADD CONSTRAINT `produtos_traje_ibfk_2` FOREIGN KEY (`IDTRAJE`) REFERENCES `traje` (`IDTRAJE`);
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 */;
|
-- View: vw_qry_tareas_distribuidos
-- DROP VIEW vw_qry_tareas_distribuidos;
CREATE OR REPLACE VIEW vw_qry_tareas_distribuidos AS
SELECT
bei.att_value_1 as Asunto,
bei.att_value_2 as Carpeta,
mt.pro_ele_inst_date_end as Finalizado,
bei.att_value_num_1 as dtb,
bei.att_value_num_2 as dtb_anx,
bei.att_value_4 as titulo,
mt.tsk_title as Tarea,
bei.att_value_8 as grupo,
mt.pro_ele_inst_user_acquired as usuario,
mt.pro_ele_inst_index, mt.mon_for, mt.env_id, mt.pro_id, mt.pro_inst_id, mt.pro_ele_inst_id, mt.pro_ele_inst_status, mt.pro_ele_inst_date_ready, mt.bus_ent_inst_id, mt.bus_ent_id, mt.pro_ele_id, mt.tsk_name, mt.tsk_title, mt.tsk_max_duration, mt.tsk_alert_duration, mt.img_path, mt.pro_name, mt.pro_title, mt.pro_ver_id, mt.pro_max_duration, mt.pro_inst_name_pre, mt.pro_inst_name_num, mt.pro_inst_name_pos, mt.pro_inst_create_user, mt.pro_inst_create_date, mt.pro_inst_end_date, mt.pro_inst_status, mt.hty_date, mt.hty_event, mt.usr_login, mt.pro_inst_ele_id_father, mt.pro_inst_warn_date, mt.pro_inst_overdue_date, mt.pro_priority
FROM vw_consults_monitor_tasks mt
JOIN bus_ent_instance bei ON mt.bus_ent_id = bei.bus_ent_id AND mt.bus_ent_inst_id = bei.bus_ent_inst_id_auto
WHERE bei.bus_ent_id= 1051 AND mt.env_id = 1 AND bei.reg_status = 0 AND mt.mon_for = 'T'::text
AND mt.pro_ele_inst_status IS NOT NULL
ORDER BY mt.pro_ele_inst_date_ready;
ALTER TABLE vw_qry_tareas_distribuidos
OWNER TO postgres;
GRANT ALL ON TABLE vw_qry_tareas_distribuidos TO postgres;
GRANT ALL ON TABLE vw_qry_tareas_distribuidos TO apia3;
|
CREATE PROC SelectImageByProductID
@ID int
AS
BEGIN
SELECT *
FROM Images
WHERE ProductID = @ID
END; |
select mol_inchi('c1ccccc1'::mol);
select mol_inchikey('c1ccccc1'::mol);
select mol_inchi('Cc1cc(C)[n+]c(C)c1'::mol);
select mol_inchikey('Cc1cc(C)[n+]c(C)c1'::mol);
select mol_inchi(mol_from_ctab((Chr(10) || Chr(10) || Chr(10) ||
' 0 0 0 0 0 0 0 0 0 0999 V2000' ||
Chr(10) ||
'M END')::cstring));
select mol_inchi('');
select mol_inchikey('');
select mol_inchi('CC1=NC=CN1'::mol);
select mol_inchikey('CC1=NC=CN1'::mol);
select mol_inchi('CC1=NC=CN1'::mol,'/FixedH');
select mol_inchikey('CC1=NC=CN1'::mol,'/FixedH');
-- Non-InChI-able molecules should return NULL.
select coalesce(mol_inchi('CC*'), '<NULL>');
select coalesce(mol_inchikey('CC*'), '<NULL>');
|
-- MySQL dump 10.16 Distrib 10.2.15-MariaDB, for debian-linux-gnu (x86_64)
--
-- Host: 127.0.0.1 Database: self
-- ------------------------------------------------------
-- Server version 10.2.15-MariaDB-10.2.15+maria~artful
/*!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 `friend_music`
--
DROP TABLE IF EXISTS `friend_music`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `friend_music` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`mid` int(11) DEFAULT NULL,
`fid` int(11) DEFAULT NULL,
`desc` varchar(4500) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_friend_music_1_idx` (`mid`),
KEY `fk_friend_music_2_idx` (`fid`),
CONSTRAINT `fk_friend_music_1` FOREIGN KEY (`mid`) REFERENCES `music` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `fk_friend_music_2` FOREIGN KEY (`fid`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `friend_music`
--
LOCK TABLES `friend_music` WRITE;
/*!40000 ALTER TABLE `friend_music` DISABLE KEYS */;
/*!40000 ALTER TABLE `friend_music` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `music`
--
DROP TABLE IF EXISTS `music`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `music` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`location` varchar(2048) DEFAULT NULL,
`singer` int(11) DEFAULT NULL,
`follow` int(11) DEFAULT NULL,
`image` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_music_1_idx` (`singer`),
CONSTRAINT `fk_music_1` FOREIGN KEY (`singer`) REFERENCES `single` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `music`
--
LOCK TABLES `music` WRITE;
/*!40000 ALTER TABLE `music` DISABLE KEYS */;
INSERT INTO `music` VALUES (1,'仰望星空','/OfficeXm/music/1.mp3',1,1244,'/OfficeXm/2/img/xiaoren.jpg');
/*!40000 ALTER TABLE `music` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `owner_music`
--
DROP TABLE IF EXISTS `owner_music`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `owner_music` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`musicid` int(11) DEFAULT NULL,
`sid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_owner_music_1_idx` (`sid`),
KEY `fk_owner_music_2_idx` (`musicid`),
CONSTRAINT `fk_owner_music_1` FOREIGN KEY (`sid`) REFERENCES `worker` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_owner_music_2` FOREIGN KEY (`musicid`) REFERENCES `music` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `owner_music`
--
LOCK TABLES `owner_music` WRITE;
/*!40000 ALTER TABLE `owner_music` DISABLE KEYS */;
/*!40000 ALTER TABLE `owner_music` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `single`
--
DROP TABLE IF EXISTS `single`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `single` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`location` varchar(45) DEFAULT NULL,
`follows` int(11) DEFAULT 0,
`name` varchar(45) DEFAULT NULL,
`sex` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `single`
--
LOCK TABLES `single` WRITE;
/*!40000 ALTER TABLE `single` DISABLE KEYS */;
INSERT INTO `single` VALUES (1,'四川省成都',1222,'张杰',1);
/*!40000 ALTER TABLE `single` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `worker`
--
DROP TABLE IF EXISTS `worker`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `worker` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL COMMENT '工作人员',
`password` varchar(45) DEFAULT NULL COMMENT '密码 MD5加密',
`sex` int(11) DEFAULT 1 COMMENT '0,女 1:男',
`address` varchar(45) DEFAULT NULL COMMENT '地址',
`phone` int(110) DEFAULT NULL COMMENT '电话',
`qq` int(11) DEFAULT NULL,
`wechat` varchar(45) DEFAULT NULL,
`department` varchar(45) DEFAULT NULL,
`position` varchar(45) DEFAULT NULL COMMENT '职位',
`desc` varchar(45) DEFAULT NULL,
`number` int(11) DEFAULT NULL COMMENT '打卡次数',
`image` varchar(10240) DEFAULT NULL COMMENT '头像',
`username` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `phone_UNIQUE` (`phone`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `worker`
--
LOCK TABLES `worker` WRITE;
/*!40000 ALTER TABLE `worker` DISABLE KEYS */;
INSERT INTO `worker` VALUES (6,'陈维维','123',1,NULL,123,NULL,NULL,NULL,NULL,NULL,NULL,'/OfficeXm/2/img/xiaoren.jpg',NULL),(12,'陈炫','123',NULL,NULL,1234,NULL,NULL,NULL,NULL,NULL,NULL,'/OfficeXm/2/img/xiaoren.jpg',NULL),(23,'1','1',1,NULL,1,NULL,NULL,NULL,NULL,NULL,NULL,'/OfficeXm/2/img/xiaoren.jpg',NULL),(24,'陈维维','111',1,NULL,111,NULL,NULL,NULL,NULL,NULL,NULL,'/OfficeXm/2/img/xiaoren.jpg',NULL),(25,'','',1,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'/OfficeXm/2/img/xiaoren.jpg',NULL),(28,'???','123',1,NULL,123456,NULL,NULL,NULL,NULL,NULL,NULL,'/OfficeXm/2/img/xiaoren.jpg',NULL),(29,'qq','000',1,NULL,0,NULL,NULL,NULL,NULL,NULL,NULL,'/OfficeXm/2/img/xiaoren.jpg',NULL);
/*!40000 ALTER TABLE `worker` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2018-06-30 17:08:16
|
-- INSERT INTO webusers VALUES ('admin', 'admin');
-- INSERT INTO webusers VALUES ('marek', 'kwiatek');
-- INSERT INTO roles VALUES (1, 'admin', 'ROLE_ADMIN');
-- INSERT INTO roles VALUES (2, 'marek', 'ROLE_USER');
|
-- +goose Up
-- SQL in this section is executed when the migration is applied.
ALTER TABLE `standups` MODIFY `text` TEXT COLLATE utf8mb4_unicode_ci NOT NULL;
-- +goose Down
-- SQL in this section is executed when the migration is rolled back.
ALTER TABLE `standups` MODIFY `text` VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL;
|
CREATE DATABASE IF NOT EXISTS inventory CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
use inventory;
-- ////////////////////////////////////////////////////////////TABLES
create table IF NOT EXISTS hibernate_sequence (next_val bigint) engine=InnoDB;
insert into hibernate_sequence values ( 1 );
create table confirmation_token_sequence (next_val bigint) engine=InnoDB;
insert into confirmation_token_sequence values ( 1 );
CREATE TABLE IF NOT EXISTS user_account (
id BIGINT NOT NULL,
creation_date TIMESTAMP,
is_account_non_expired BOOLEAN,
is_account_non_locked BOOLEAN,
is_credentials_non_expired BOOLEAN,
is_enabled BOOLEAN,
modified_date TIMESTAMP,
password VARCHAR(255),
user_roles VARCHAR(255),
username VARCHAR(255) unique,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS supplier (
id VARCHAR(36) NOT NULL,
address VARCHAR(255),
created_date TIMESTAMP,
first_name VARCHAR(255),
last_name VARCHAR(255),
modified_date TIMESTAMP,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS activity (
id BIGINT NOT NULL,
created TIMESTAMP,
last_updated TIMESTAMP,
entity VARCHAR(255),
expires VARCHAR(255),
ip VARCHAR(255),
parameter VARCHAR(255),
request_method VARCHAR(255),
response_status INTEGER,
url VARCHAR(255),
user_agent VARCHAR(255),
user_id BIGINT,
PRIMARY KEY (id),
foreign key (user_id) references user_account(id)
);
CREATE TABLE IF NOT EXISTS customer (
id VARCHAR(36) NOT NULL,
address VARCHAR(255),
created_date TIMESTAMP,
first_name VARCHAR(255),
last_name VARCHAR(255),
modified_date TIMESTAMP,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS product (
id VARCHAR(36) NOT NULL,
created_date TIMESTAMP,
modified_date TIMESTAMP,
name VARCHAR(255),
price BIGINT,
sale_price BIGINT,
description VARCHAR(255),
image_available bool default false,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS purchase_invoice (
id VARCHAR(36) NOT NULL,
created_date TIMESTAMP,
modified_date TIMESTAMP,
supplier_id VARCHAR(36),
PRIMARY KEY (id),
foreign key (supplier_id) references supplier (id)
);
CREATE TABLE IF NOT EXISTS purchase_transaction (
id VARCHAR(36) NOT NULL,
created_date TIMESTAMP,
description VARCHAR(255),
modified_date TIMESTAMP,
price BIGINT,
quantity BIGINT,
invoice_id VARCHAR(36),
product_id VARCHAR(36) ,
product_name varchar(255),
PRIMARY KEY (id),
foreign key (invoice_id) references purchase_invoice (id),
foreign key (product_id) references product (id)
);
CREATE TABLE IF NOT EXISTS sale_invoice (
id VARCHAR(36) NOT NULL,
created_date TIMESTAMP,
modified_date TIMESTAMP,
customer_id VARCHAR(36),
PRIMARY KEY (id),
foreign key (customer_id) references customer (id)
);
CREATE TABLE IF NOT EXISTS sale_transaction (
id VARCHAR(36) NOT NULL,
created_date TIMESTAMP,
description VARCHAR(255),
modified_date TIMESTAMP,
price BIGINT,
quantity BIGINT,
invoice_id VARCHAR(36),
product_id VARCHAR(36) ,
product_name varchar(255),
PRIMARY KEY (id),
foreign key (invoice_id) references sale_invoice (id),
foreign key (product_id) references product (id)
);
CREATE TABLE IF NOT EXISTS user_account_user_permissions (
user_account_id BIGINT NOT NULL,
user_permissions VARCHAR(255),
foreign key (user_account_id) references user_account (id)
);
CREATE TABLE IF NOT EXISTS user_session (
username VARCHAR(255) NOT NULL,
token LONGTEXT,
PRIMARY KEY (username)
);
CREATE TABLE IF NOT EXISTS user_profile (
id VARCHAR(36) NOT NULL,
created_date TIMESTAMP,
first_name VARCHAR(255),
last_name VARCHAR(255),
email VARCHAR(255),
image_available bool default false,
modified_date TIMESTAMP,
account_id BIGINT NOT NULL,
PRIMARY KEY (id),
foreign key (account_id) references user_account (id)
);
CREATE TABLE IF NOT EXISTS confirmation_token (
id BIGINT NOT NULL,
confirm_at TIMESTAMP,
created_date TIMESTAMP NOT NULL,
expires_at TIMESTAMP NOT NULL,
token VARCHAR(255) NOT NULL,
user_profile_id VARCHAR(36) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (user_profile_id) REFERENCES user_profile (id)
);
-- ////////////////////////////////////////////////////////////CONSTRAINTS
-- ////////////////////////////////////////////////////////////INDEXES
-- create index IDXkiyy7m3fwm4vo5nil9ibp5846 on customer (first_name, last_name);
ALTER TABLE customer ADD INDEX (first_name, last_name);
-- create index IDXnejv48oro0mjt6v13jl7t3l8k on supplier (first_name, last_name);
ALTER TABLE supplier ADD INDEX (first_name, last_name);
-- create index IDXjmivyxk9rmgysrmsqw15lqr5b on product (name);
ALTER TABLE product ADD INDEX (name);
-- create index IDXcastjbvpeeus0r8lbpehiu0e4 on user_account (username);
ALTER TABLE user_account ADD INDEX (username);
-- create index IDXshil01lken9uud5fvqe7g1t58 on user_profile (first_name, last_name);
ALTER TABLE user_profile ADD INDEX (first_name, last_name);
ALTER TABLE confirmation_token ADD INDEX (token);
-- ////////////////////////////////////////////////////////////PRODUCT_VIEW
CREATE OR REPLACE VIEW product_view AS
(SELECT
p.id ,
p.name ,
p.description ,
p.price ,
p.sale_price ,
p.created_date ,
p.image_available ,
CAST((CASE WHEN it.quantity IS NOT NULL THEN it.quantity ELSE 0 END ) - (CASE
WHEN s.quantity IS NOT NULL THEN s.quantity
ELSE 0
END) AS UNSIGNED) AS quantity
FROM
product p
LEFT JOIN
(SELECT
pt.product_id, (SUM(pt.quantity)) AS quantity
FROM
purchase_transaction pt
GROUP BY pt.product_id) AS it ON p.id = it.product_id
LEFT JOIN
(SELECT
st.product_id, (SUM(st.quantity)) AS quantity
FROM
sale_transaction st
GROUP BY st.product_id) AS s ON p.id = s.product_id) LIMIT 1000;
-- ////////////////////////////////////////////////////////////INVOICE_VIEW
CREATE OR REPLACE VIEW invoice_view AS
(SELECT
pi.id AS id,
CONCAT(first_name, ' ', last_name) AS NAME,
'purchase' AS TYPE,
created_date
FROM
purchase_invoice pi
LEFT JOIN
(SELECT
id, first_name, last_name
FROM
supplier) AS s ON pi.supplier_id = s.id
UNION ALL SELECT
si.id AS id,
CONCAT(first_name, ' ', last_name) AS NAME,
'sale' AS TYPE,
created_date
FROM
sale_invoice si
LEFT JOIN
(SELECT
id, first_name, last_name
FROM
customer) AS c ON si.customer_id = c.id)
LIMIT 1000;
-- ////////////////////////////////////////////////////////////TRANSACTION_VIEW
CREATE OR REPLACE VIEW transaction_view AS
(SELECT
tr.id,
tr.product_id,
tr.product_name,
tr.price,
tr.quantity,
tr.TYPE,
tr.created_date,
p.image_available
FROM
(SELECT
*, 'purchase' AS TYPE
FROM
purchase_transaction tr UNION SELECT
*, 'sale' AS TYPE
FROM
sale_transaction st) AS tr
LEFT JOIN (SELECT id as i , image_available FROM
product pr) AS p ON tr.product_id = p.i
) LIMIT 1000;
|
# =============================================================================================
# Created by: Laercio Serra (laercio.serra@gmail.com)
# About this Code: script to move data from stage area to data warehouse into Hive
# =============================================================================================
# Version 1: creating the code
# =============================================================================================
%sql
-- Loading data to BIGTABLE_SALES
SELECT
g.transaction_id as transaction_id
, NVL(g.transaction_ip_address, 'NA') as transaction_ip_address
, NVL(g.transaction_user_info.email, 'NA') as transaction_email
, NVL(g.transaction_user_info.login_method, 'NA') as transaction_login_method
, NVL(g.transaction_user_info.verified, false) as transaction_verified
, NVL(g.mtid, 'NA') as mtid
, NVL(g.shipping_details.city, 'NA') as shipping_city
, NVL(g.shipping_details.country, 'NA') as shipping_country
, NVL(g.shipping_details.country_code, 'NA') as shipping_country_code
, NVL(g.shipping_details.name, 'NA') as shipping_name
, NVL(g.shipping_details.phone_number, 'NA') as shipping_phone_number
, NVL(g.shipping_details.state, 'NA') as shipping_state
, NVL(g.shipping_details.state_abbreviation, 'NA') as shipping_state_abbreviation
, NVL(g.shipping_details.street_address1, 'NA') as shipping_address1
, NVL(g.shipping_details.street_address2, 'NA') as shipping_address2
, NVL(g.shipping_details.zipcode, 'NA') as shipping_zipcode
, NVL(g.time, CURRENT_TIMESTAMP) as transaction_time
, NVL(g.subtotal, 0.0) as transaction_subtotal
, NVL(g.total, 0.0) as transaction_total
, g.user_id as user_id
, d.product_id as product_id
, NVL(d.image_url, 'NA') as image_url
, NVL(d.is_wish_express, false) as is_wish_express
, NVL(d.merchant_display_name, 'NA') as merchant_display_name
, d.merchant_id as merchant_id
, NVL(d.merchant_name, 'NA') as merchant_name
, NVL(d.merchant_price, 0.0) as merchant_price
, NVL(d.name, 'NA') as product_name
, NVL(d.original_price, 0.0) as original_price
, NVL(d.original_shipping, 0.0) as original_shipping
, NVL(d.quantity, 0) as quantity
, NVL(d.shipped_date, CURRENT_DATE) as shipped_date
, NVL(d.size, 'NA') as size
, d.variation_id as variation_id
FROM
wishhack.orderDetails_full_23062018_stg g
LATERAL VIEW
explode(transaction_items) t as d
WHERE
g.transaction_id IS NOT NULL
AND g.user_id IS NOT NULL
AND g.time IS NOT NULL
AND d.product_id IS NOT NULL
AND d.merchant_id IS NOT NULL
AND d.variation_id IS NOT NULL |
/*
################################################################################
Migration script to add a column for OrPerCopyRecipRange to table Association
Designed for execution with Flyway database migrations tool; this should be
automatically run to completely generate the schema that is out-of-the-box
compatibile with the GOCI model (see
https://github.com/tburdett/goci/tree/2.x-dev/goci-core/goci-model for more).
author: Dani Welter
date: April 22nd 2015
version: 1.9.9.038 (pre 2.0)
################################################################################
--------------------------------------------------------
-- Add OR_PER_COPY_RECIP_RANGE to ASSOCIATION
--------------------------------------------------------
*/
ALTER TABLE "ASSOCIATION" ADD "OR_PER_COPY_RECIP_RANGE" VARCHAR2(255 CHAR);
|
SELECT
ADJUSTMENT_SEQ_NO, --债权分类调整履历号
ADJUSTMENT_APPLY_NO, --申请编号
ADJUSTED_TYPE, --调整类型
BEFORE_CLASSIFICATION_BASEDATE AS H_BEFORE_CLASSIFICATION_BASEDATE, --调整前分类基准日
BEFORE_CLASSIFICATION_CODE, --调整前分类编码
AFTER_CLASSIFICATION_CODE AS H_AFTER_CLASSIFICATION_CODE, --调整后分类编码
ADJUSTMENT_USER, --调整担当者
CONVERT(varchar(100),ADJUSTED_DATE, 111)+' '+CONVERT(varchar(100), ADJUSTED_DATE, 8) AS H_ADJUSTED_DATE, --调整日期
ADJUSTED_REASON AS H_APPLY_ADJUSTED_REASON, --调整理由
A.MODIFY_USER, --新規者/更新者
A.MODIFY_DATE, --新規日付/更新日付
CASE WHEN /*countryId*/''= /*chinaId*/ THEN
B.CLASSIFICATION_STRING1
ELSE
CASE WHEN /*countryId*/'' = /*japanId*/ THEN
B.CLASSIFICATION_STRING2
ELSE
CASE WHEN /*countryId*/''= /*enId*/ THEN
B.CLASSIFICATION_STRING3
END
END
END AS H_BEFORE_CLASSIFICATION,
CASE WHEN /*countryId*/''= /*chinaId*/ THEN
C.CLASSIFICATION_STRING1
ELSE
CASE WHEN /*countryId*/'' = /*japanId*/ THEN
C.CLASSIFICATION_STRING2
ELSE
CASE WHEN /*countryId*/''= /*enId*/ THEN
C.CLASSIFICATION_STRING3
END
END
END AS H_AFTER_CLASSIFICATION,
-- B.コード名称 AS 调整类型名
D.CODE_NAME AS H_ADJUSTED_TYPE,
-- C.ユーザー名 AS 操作人
E.USER_NAME AS H_ADJUSTMENT_USER
FROM CRC_ADJUSTMENT_APPLY_HISTORY A
LEFT JOIN CRC_CLASSIFICATION_MASTER B
ON A.BEFORE_CLASSIFICATION_CODE = B.CLASSIFICATION_CODE
LEFT JOIN CRC_CLASSIFICATION_MASTER C
ON A.AFTER_CLASSIFICATION_CODE = C.CLASSIFICATION_CODE
LEFT JOIN
CODE_MASTER D
ON
-- AND コードマスタ(D).コード種類=「344 综合评定调整类型」(+)
D.CODE_TYPE = /*synAdjustType*/
-- AND コードマスタ(D).国ID = 参数.国ID(+)
AND D.COUNTRY_ID = /*countryId*/''
-- AND 债权分类调整履历(A).调整类型 = コードマスタ(B).コードID (+)
AND A.ADJUSTED_TYPE = D.CODE_ID
LEFT JOIN
LEASE_USER E
ON
-- AND 债权分类调整履历(E).调整担当者 = ユーザーマスタ( C ).ユーザーID(+)
A.ADJUSTMENT_USER = E.USER_ID
WHERE
A.ADJUSTMENT_APPLY_NO = /*adjustmentApplyNo*/''
--A.调整类型 <> 4:退回
/*IF (adjustReturn != null)*/
AND A.ADJUSTED_TYPE <> /*adjustReturn*/
/*END*/
--A.调整类型 <> 3:否决
/*IF (adjustDeny != null)*/
AND A.ADJUSTED_TYPE <> /*adjustDeny*/
/*END*/
ORDER BY A.ADJUSTMENT_SEQ_NO DESC
|
drop table if exists person;
create table person(first varchar(255), last varchar(255), title varchar(255)) ENGINE=MyISAM;
insert into person values('Mark', 'Florence', 'Mr');
insert into person values('Lucky', 'Florence', 'Cat');
insert into person values('Lynn', 'Hendrickson', 'Ms');
insert into person values('Max', 'Hendrickson', 'Cat');
drop table if exists title;
create table title(title varchar(255), description varchar(255)) ENGINE=MyISAM;
insert into title values('Cat', 'I am a cat');
insert into title values('Mr', 'I am a man');
insert into title values('Ms', 'I am a woman');
|
CREATE TABLE public.da_ward (
ward_cd character varying(8),
ward_name character varying(32),
ward_group_cd character varying(8),
record_status character(1),
loc_cd character varying(16),
org_cd character varying(8),
grp_cd character varying(8),
dw_facility_cd character varying(16),
dw_job_run_no bigint,
dw_last_updated_dt timestamp without time zone,
dw_row_id character varying(128)
);
|
SELECT mir_vst.vst_end_dtime
, mir_pyr_plan.pyr_cd
, mir_pyr_plan.bl_drg_cost_weight
, mir_pyr_plan.pt_id
, mir_vst.len_of_stay
, mir_pyr_plan.bl_drg_no
, mir_vst.pt_type
, mir_pract_mstr.pract_rpt_name
, mir_vst.hosp_svc
, pyr_dim_v.pyr_group2
, mir_vst.prim_pract_no
, mir_pyr_plan.pyr_seq_no
, mir_vst.vst_end_date
, mir_pyr_plan.bl_drg_schm
, mir_vst.vst_type_cd
, mir_vst.tot_chg_amt
FROM (
(
SMSPHDSSS0X0.smsmir.mir_pyr_plan mir_pyr_plan
LEFT OUTER JOIN SMSPHDSSS0X0.smsmir.mir_vst_rpt mir_vst
ON mir_pyr_plan.pt_id = mir_vst.pt_id
AND mir_pyr_plan.pt_id_start_dtime = mir_vst.pt_id_start_dtime
)
LEFT OUTER JOIN SMSPHDSSS0X0.smsdss.pyr_dim_v pyr_dim_v
ON mir_pyr_plan.pyr_cd = pyr_dim_v.pyr_cd
AND mir_pyr_plan.src_sys_id = pyr_dim_v.src_sys_id
)
LEFT OUTER JOIN SMSPHDSSS0X0.smsmir.mir_pract_mstr mir_pract_mstr
ON mir_vst.src_sys_id = mir_pract_mstr.src_sys_id
AND mir_vst.prim_pract_no = mir_pract_mstr.pract_no
WHERE mir_pyr_plan.pyr_seq_no=1
AND mir_vst.hosp_svc not in ('epy', 'psy')
AND mir_vst.vst_end_dtime >= '2017-06-01 00:00:00'
AND mir_vst.vst_end_dtime < '2017-11-01 00:00:00'
AND mir_vst.vst_type_cd = 'I'
AND mir_vst.tot_chg_amt <> 0
|
DROP TABLE bill;
CREATE TABLE `bill` (
`InvoiceNo` char(50) NOT NULL DEFAULT '0',
`ItemNo` char(50) NOT NULL DEFAULT '1',
`BrandName` varchar(50) DEFAULT NULL,
`DosageForm` varchar(50) DEFAULT NULL,
`Quantity` int(11) DEFAULT NULL,
`ExpirationDate` date DEFAULT NULL,
`UnitPrice` double DEFAULT NULL,
`ItemPrice` double DEFAULT NULL,
`Discount` double DEFAULT NULL,
`HealthTips` varchar(50) DEFAULT NULL,
PRIMARY KEY (`InvoiceNo`,`ItemNo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO bill VALUES("1001","1","Panadol","Syrup","3","2017-04-08","130","9","","");
INSERT INTO bill VALUES("1701085","1","","","","","","","","");
INSERT INTO bill VALUES("1701086","1","Panadol","Syrup","3","2017-06-12","0","6","","");
INSERT INTO bill VALUES("1701087","1","Panadol","Syrup","3","2017-04-08","130","9","","");
DROP TABLE complete;
CREATE TABLE `complete` (
`OrderNo.` int(100) NOT NULL,
`NIC` varchar(12) NOT NULL,
`DP` varchar(15) NOT NULL,
`Address` varchar(255) NOT NULL,
`DPTime` time NOT NULL,
`Telephone` char(50) NOT NULL,
`Email` varchar(60) NOT NULL,
`Image1` varchar(255) NOT NULL,
`ImageName1` varchar(64) NOT NULL,
`Image2` varchar(255) NOT NULL,
`ImageName2` varchar(64) NOT NULL,
`Image3` varchar(255) NOT NULL,
`ImageName3` varchar(64) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO complete VALUES("131","933560621 ","Pickup","-","21:30:00","112422628","lasithd2@gmail.com","photo/1.JPG","1.JPG","No copy"," ","No copy"," ");
INSERT INTO complete VALUES("151","933560621 ","Pickup","-","12:00:00","112422628","lasithd2@gmail.com","photo/1.JPG","1.JPG","photo/2.JPG","2.JPG","No copy"," ");
DROP TABLE customer;
CREATE TABLE `customer` (
`NIC` varchar(13) NOT NULL,
`FName` varchar(50) NOT NULL,
`LName` varchar(50) NOT NULL,
`Gender` varchar(10) NOT NULL,
`DOB` date NOT NULL,
`Address` varchar(255) NOT NULL DEFAULT 'NOT SET',
`Status` varchar(10) NOT NULL DEFAULT 'NOT SET',
`Contact` char(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`Password` varchar(255) NOT NULL,
`BloodGroup` varchar(50) DEFAULT 'NOT SET',
`AllergicDrugs` varchar(50) NOT NULL DEFAULT 'NOT SET',
PRIMARY KEY (`NIC`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO customer VALUES("933560514V","Kasun","Kumararathna","male","1993-12-11",""," ","0718124190","kasun@gmail.com","$2y$10$1U.0q1F3UI31sEqb6mrZIeo6bFqiJXEGVwQdDbm3ZM9vvhvs1Z3wq","NOT SET","NOT SET");
INSERT INTO customer VALUES("933560524V","Vishva","Sudantha","male","1993-12-01","Kalutara","Single","0719124190","ab@gmail.com","$2y$10$5Neyc9GagcyeYHF8KSL7cOvimGTHHHq/6x1YTpOmqhK7EQDzZA9N6"," ","Cordarone");
INSERT INTO customer VALUES("935780942V","Ushani","Nayanathara","","1993-03-18",""," ","0710598705","ushani93@gmail.com","$2y$10$.mLztOHkBhP8F8IFOhyC5OFwl.jkHrZib.AUstaZZjsjlVJS0i6Ge","NOT SET","NOT SET");
INSERT INTO customer VALUES("955643091V","Amal","Perera","male","1995-12-12",""," ","0719938109","a@gmail.com","$2y$10$1wXc9z2m035J8BXSwr1Rs..0RfTykwsBBiGiT.hxoQAuZGsi8mcMu","NOT SET","NOT SET");
DROP TABLE doctor;
CREATE TABLE `doctor` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`category` varchar(50) NOT NULL,
`hospital` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=latin1;
INSERT INTO doctor VALUES("1","Dr. Abewardhana","Cancer Specialist","Distric Base Hospital - Gampaha");
INSERT INTO doctor VALUES("2","Dr. Prasad Abeysinghe","Cancer Specialist","Base Hospital - Watthupitiwala");
INSERT INTO doctor VALUES("3","Dr. AgeyGunasekara","Denito Urinary Surgeon","Teaching Hospital - Ragama");
INSERT INTO doctor VALUES("4","Dr. S. C. Abeysooriya","Neuro Surgeon","Distric Base Hospital - Gampaha");
INSERT INTO doctor VALUES("5","Dr. M. Abeywardhana","Gynaecologist","Distric Hospital - Minuwangoda");
INSERT INTO doctor VALUES("6","Dr. R. Ajanthan","Paediatrician","District Hospital - Divulapitiya ");
INSERT INTO doctor VALUES("7","Dr. S. F. L. Akbar ","Gynaecologist","District Hospital - Mirigama ");
INSERT INTO doctor VALUES("8","Dr. Dasanthi Akmeemana ","Psychiatrist","Sethma Hospital - Gampaha ");
INSERT INTO doctor VALUES("9","Dr. K. Alagarathnam ","Surgeon","District Base Hospital - Kiribathgoda ");
INSERT INTO doctor VALUES("10","Dr. A. T. Alibhoy ","Neuro Physician","Peripheral Hospital - Pamunuwa ");
INSERT INTO doctor VALUES("11","Dr. Sanjaya AbeyGunasekara","Paediatric Surgeon","Distric Base Hospital - Gamapaha");
INSERT INTO doctor VALUES("12","Dr. Ranjith Almeida ","Gynaecologist","Rural Hospital - Udupila ");
INSERT INTO doctor VALUES("13","Dr. Stanley Amarasekara ","Cardiologist","Rural Hospital - Biyagama ");
INSERT INTO doctor VALUES("14","Dr. Sarath Amarasekara","Cardiologist","Vijaya Kumarathunga Memorial Hospital - Seeduwa ");
INSERT INTO doctor VALUES("15","Dr. N. Amarasekara ","Physician","Rural Hospital - Kapala Kanda ");
INSERT INTO doctor VALUES("16","Dr. Binara Amarasinghe ","Eye Surgeon","Peripheral Hospital - Radawana ");
INSERT INTO doctor VALUES("17","Dr. Anil P. Ambawatta ","Surgeon","Peripheral Hospital - Akkaragama ");
INSERT INTO doctor VALUES("19","Dr. Yasantha Ariyarathna ","Oncologist","Peripheral Hospital - Bokalagama ");
INSERT INTO doctor VALUES("20","Dr. D. N. Athukorala ","Dermatologist","Rural Hospital - Hiripitiya ");
INSERT INTO doctor VALUES("31","Dr. Abeyrathne","Heart Surgeon","Gampaha District Hospital ");
DROP TABLE drug;
CREATE TABLE `drug` (
`DrugNo` char(50) NOT NULL,
`GeneticName` varchar(50) NOT NULL,
`BrandName` varchar(20) NOT NULL,
`DosageForm` varchar(20) NOT NULL,
`Alternatives` varchar(150) DEFAULT NULL,
`Compositions` varchar(100) NOT NULL,
`DosePerPerson` varchar(50) NOT NULL,
`Strength` varchar(5) NOT NULL,
`healthTips` varchar(500) DEFAULT NULL,
`storage` varchar(500) DEFAULT NULL,
PRIMARY KEY (`DrugNo`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO drug VALUES("010101","Paracetamol","Panadol","Tablet","Calpol, Disprol","Paracetamol, Sucrose, Sorbitol","2 tablets 3 times a day","500mg","Stop taking the medication and seek immediate medical attention if there are signs of a serious allergic reaction, difficulty breathing, swelling of face or throat","Any place");
INSERT INTO drug VALUES("010102","Paracetamol","Panadol","Syrup","Calpol, Disprol","Paracetamol, Sucrose, Sorbitol","1 spoon three times a day (8kg)","120ml","Stop taking the medication and seek immediate medical attention if there are signs of a serious allergic reaction, difficulty breathing, swelling of face or throat","Any place");
INSERT INTO drug VALUES("010201","Paracetamol","Disprol","Tablet","Panadol, Calpol","Paracetamol, Sucrose, Sorbitol","2 tablets three times a day","250mg","Stop taking the medication and seek immediate medical attention if there are signs of a serious allergic reaction, difficulty breathing, swelling of face or throat","");
INSERT INTO drug VALUES("010202","Paracetamol","Disprol","Syrup","Panadol, Calpol","Paracetamol, Sucrose, Sorbitol","2 tablets 3 times a day","500mg","Stop taking the medication and seek immediate medical attention if there are signs of a serious allergic reaction, difficulty breathing, swelling of face or throat","Any place");
INSERT INTO drug VALUES("010301","Paracetamol","Calpol","tablet","Panadol, Disprol","Paracetamol, Sucrose, Sorbitol","2 tablets 3 times a day","500mg","Stop taking the medication and seek immediate medical attention if there are signs of a serious allergic reaction, difficulty breathing, swelling of face or throat","Any place");
INSERT INTO drug VALUES("010302","Paracetamol","Calpol","Syrup","Panadol, Disprol","Paracetamol, Sucrose, Sorbitol","1 spoon three times a day","120ml","Stop taking the medication and seek immediate medical attention if there are signs of a serious allergic reaction, difficulty breathing, swelling of face or throat","");
INSERT INTO drug VALUES("010401","Oaracetamol","Cryptol","Tablet","","Paracetamol, Sorbitol","2 tablets 3 times a day","500mg","Stop taking the medication and seek immediate medical attention if there are signs of a serious allergic reaction, difficulty breathing, swelling of face or throat","Any place");
INSERT INTO drug VALUES("020401","Bupropion"," Wellbutrin XL","Tablet","Wellbutrin SR","bupropion hydrochloride","1 tablet 2 times a day","150mg","Stop taking the medication and seek immediate medical attention if there are signs of a serious allergic reaction, difficulty breathing, swelling of face or throat","Any place");
INSERT INTO drug VALUES("030501","Amiodarone","CordaroneIV","Tablet","Nexterone, Cordarone, Pacerone","2-butyl-3-benzofuranyl 4-[2-(diethylamino)-ethoxy]-3, 5-diiodophenyl ketone hydrochloride","2 tablet 3 times ","500mg","If taken during pregnancy or breastfeeding it can cause problems in the baby","Store in a cool, dry place, away from direct heat and light");
INSERT INTO drug VALUES("030601","Amiodarone","Nexterone","Tablet"," Cordarone, Pacerone, CordaroneIV","2-butyl-3-benzofuranyl 4-[2-(diethylamino)-ethoxy]-3, 5-diiodophenyl ketone hydrochloride","2 tablet 3 times","500mg","If taken during pregnancy or breastfeeding it can cause problems in the baby","Store in a cool, dry place, away from direct heat and light");
INSERT INTO drug VALUES("030701","Amiodarone","Pacerone","Tablet","Nexterone, Cordarone, CordaroneIV","2-butyl-3-benzofuranyl 4-[2-(diethylamino)-ethoxy]-3, 5-diiodophenyl ketone hydrochloride","2 tablet 3 times","500mg","If taken during pregnancy or breastfeeding it can cause problems in the baby","Store in a cool, dry place, away from direct heat and light");
INSERT INTO drug VALUES("030801","Amiodarone ","Cordarone","Tablet","Pacerone, Nexterone, Cordarone IV","2-butyl-3-benzofuranyl 4-[2-(diethylamino)-ethoxy]-3, 5-diiodophenyl ketone hydrochloride","2 tablet three times","500mg","If taken during pregnancy or breastfeeding it can cause problems in the baby","Store in a cool, dry place, away from direct heat and light");
INSERT INTO drug VALUES("040901","Altretamine","Hexalen ","Tablet","","Tenormin, altretamine","1 capsule three times a day","250mg","","");
INSERT INTO drug VALUES("051001","Bupropion","Wellbutrin SR","Tablet","Wellbutrin XL","bupropion hydrochloride","1 tablet 2 times a day","150mg","Stop taking bupropion and get medical help right away if you have any very serious side effects, including: seizure, eye pain/swelling/redness, widened pupils, vision changes (such as seeing rainbows around lights at night, blurred vision).","Any place");
INSERT INTO drug VALUES("061103","Capsaissin","Rezil","Cream","Quenteza, Theragen","Dihydrocapsaicin, Nodihydrocapsaicin, Homodihydrocaapsaicin","Up to 4 times daily","120mg","If blurred vision,dizziness,nervousness or fast heartbeat occur, stop using and meet your doctor","Store at room temperature, away from heat, moisture, and light.");
INSERT INTO drug VALUES("061203","Capsaisin","Theragen","Cream","Quenteza, Rezil","Dihydrocapsaicin, Nodihydrocapsaicin, Homodihydrocaapsaicin","Up to 4 times daily","120mg","If blurred vision,dizziness,nervousness or fast heartbeat occur, stop using and meet your doctor","Store at room temperature, away from heat, moisture, and light.");
INSERT INTO drug VALUES("061303","Capsaisin","Qutenza","Cream","Theragen, Rezil","Dihydrocapsaicin, Nodihydrocapsaicin, Homodihydrocaapsaicin","up to 4 times daily","120mg","If blurred vision,dizziness,nervousness or fast heartbeat occur, stop using and meet your doctor","Store at room temperature, away from heat, moisture, and light.");
INSERT INTO drug VALUES("081401","Benzoate","Zonatuss","Tablet","Tessalon","Procaine, Tetracaine","1 tablet 2 times a day","125mg","Tell your doctor right away if any mental/mood changes, loss of feeling in the chest, burning in the eyes occur.","Any place");
INSERT INTO drug VALUES("081501","Benzonatate","Tessalon","Tablet","Zonatuss","procaine, tetracaine","1 tablet two times a day","125mg","Tell your doctor right away if any mental/mood changes, loss of feeling in the chest, burning in the eyes occur.","Any place");
DROP TABLE drugstock;
CREATE TABLE `drugstock` (
`StockNo` char(50) NOT NULL,
`BrandName` varchar(50) NOT NULL DEFAULT '0',
`DosageForm` varchar(50) NOT NULL DEFAULT '0',
`SupplierName` varchar(50) NOT NULL DEFAULT '0',
`PurchaseDate` date NOT NULL,
`ExpireDate` date NOT NULL,
`Expired` int(3) NOT NULL DEFAULT '0',
`QtyType` varchar(50) NOT NULL,
`RemainingQty` varchar(50) NOT NULL,
`OrderedQty` varchar(50) NOT NULL DEFAULT '0',
`ReturnPolicy` int(11) NOT NULL DEFAULT '0',
`RetailPrice` double NOT NULL DEFAULT '0',
`OrderedPrice` double NOT NULL DEFAULT '0',
`Discount` double NOT NULL DEFAULT '0',
`ProfitMargin` double NOT NULL DEFAULT '0',
PRIMARY KEY (`StockNo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO drugstock VALUES("010101","Panadol","Tablet","Hemas Pharmaceuticals","2016-11-12","2019-01-12","0","No.ofBoxes","250","0","0","110","100","1","1");
INSERT INTO drugstock VALUES("010201","Panadol ","Syrup ","Hemas Pharmaceuticals ","2016-11-08","2017-04-08","0","No. of Bottles","20","2000","1","130","100","3","2");
INSERT INTO drugstock VALUES("010202","Panadol","Syrup","Glaxo Healthcare (Pvt) Ltd ","2016-11-12","2017-06-12","0","No. of Bottles","8","2000","1","110","100","2","2");
INSERT INTO drugstock VALUES("010203","Panadol","Syrup","Meditech","2017-01-12","2019-01-13","0","No. of Bottles","12","2000","0","110","110","0","0");
INSERT INTO drugstock VALUES("020103","Disprol","Tablet","Meditech","2016-06-12","2018-11-13","0","No.of Packets","100","1000","1","65","65","0","0");
INSERT INTO drugstock VALUES("020201","Calpol","Syrup","Hemas Pharmaceuticals","2016-09-05","2018-01-12","0","No.of Bottles","40","1000","0","143","130","1","1");
INSERT INTO drugstock VALUES("020203","Disprol","Syrup","Meditech","2016-01-14","2019-01-12","0","No.ofBottles","300","400","0","100","100","0","1");
INSERT INTO drugstock VALUES("020204","Calpol","Tablet","Arogya","2016-02-12","2020-01-12","0","No.ofBottles","500","1000","0","550","500","1","0");
INSERT INTO drugstock VALUES("040101","Wellbutrin SR","Tablet","Hemas Pharmaceuticals","2016-11-12","2019-01-12","0","No. of Packets","123","400","1","129.8","118","1","2");
INSERT INTO drugstock VALUES("040102","Wellbutrin XL","Tablet","Glaxo Healthcare (Pvt) Ltd","2016-01-12","2019-01-12","0","No. of Packets","243","1000","0","121","110","2","2");
INSERT INTO drugstock VALUES("040104","Wellbutrin XL","Tablet","Arogya","2016-11-30","2019-01-12","0","No. of Packets","250","1000","1","132","120","1","2");
INSERT INTO drugstock VALUES("050101","Cordarone","Tablet","Hemas Pharmaceuticals","2015-01-13","2018-01-12","0","No.of Packets","250","400","1","84","70","2","1");
INSERT INTO drugstock VALUES("050103","CordaroneIV","Tablet","Meditech","2016-04-12","2018-11-22","0","No.of Packets","200","1000","1","96.2","81","2","2");
INSERT INTO drugstock VALUES("060104","Nexterone","Tablet","Arogya","2016-11-12","2018-11-12","0","No. of Packets","300","500","1","82.5","75","1","1");
INSERT INTO drugstock VALUES("070103","Pacerone","Tablet","Meditech","2016-10-12","2018-01-12","0","No. of Packets","200","1000","1","80.3","73","1","2");
INSERT INTO drugstock VALUES("070104","Pacerone","Tablet","Arogya","2015-11-12","2017-01-12","120","No.of Packets","120","600","1","71.07","69","3","2");
INSERT INTO drugstock VALUES("090102","Hexalen","Tablet","Glaxo Healthcare (Pvt) Ltd","2016-11-12","2018-01-12","0","No.of Packets","30","200","0","120","100","2","2");
INSERT INTO drugstock VALUES("100103","Wellbutrin SR","Tablet","Meditech","2015-03-15","2017-01-12","45","No. of Packets","45","2000","1","136.4","124","2","2");
INSERT INTO drugstock VALUES("110301","Rezil","Cream","Hemas Pharmaceuticals","2016-05-10","2018-07-16","0","No.of Tubes","200","1000","1","66","60","1","2");
INSERT INTO drugstock VALUES("120301","Quetenza","Cream","Hemas Pharmaceuticals","2016-11-12","2018-11-12","0","no. of Tubes","75","400","1","143","130","1","2");
INSERT INTO drugstock VALUES("120302","Theragen","Cream","Glaxo Healthcare (Pvt) Ltd","2015-01-12","2016-12-31","100","No.of Tubes","100","700","1","137.5","125","2","2");
INSERT INTO drugstock VALUES("140101","Zonatuss","Tablet","Hemas Pharmaceuticals","2016-11-02","2018-11-22","0","No. of Packets","150","1500","1","51","50","2","2");
INSERT INTO drugstock VALUES("150102","Tessalon","Tablet","Glaxo Healthcare (Pvt) Ltd","2016-01-12","2018-01-12","0","No. of Packets","200","2000","1","81.6","80","2","1");
DROP TABLE hospital;
CREATE TABLE `hospital` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`hospitalname` varchar(50) NOT NULL,
`location` varchar(50) NOT NULL,
`telephonenum` char(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=61 DEFAULT CHARSET=latin1;
INSERT INTO hospital VALUES("1","Base Hospital","Wattupitiwala","0332959262");
INSERT INTO hospital VALUES("2","Distric Base Hospita
\nl","Negambo","0332959263");
INSERT INTO hospital VALUES("3","Distric Base Hospital","Gampaha","0332222629");
INSERT INTO hospital VALUES("4","Distric Hospital","Minuwangoda","0332959264");
INSERT INTO hospital VALUES("5","Distric Hospital","Dompe","0332959265");
INSERT INTO hospital VALUES("7","District Hospital","Minuwangoda","0332959267");
INSERT INTO hospital VALUES("8","Peripheral Hospital","Pamunuwa","0332959268");
INSERT INTO hospital VALUES("9","Teaching Hospital","Ragama","0332959261");
INSERT INTO hospital VALUES("10","Sethma Hospital ","Gampaha ","0335963874");
INSERT INTO hospital VALUES("11","District Hospital","Divulapitiya ","0312246261");
INSERT INTO hospital VALUES("12","District Hospital ","Mirigama ","0332273261");
INSERT INTO hospital VALUES("13","District Base Hospital ","Kiribathgoda ","0112911493");
INSERT INTO hospital VALUES("14","Peripheral Hospital ","Pamunuwa ","112236622");
INSERT INTO hospital VALUES("15","Rural Hospital ","Udupila ","0112402237");
INSERT INTO hospital VALUES("16","Rural Hospital","Biyagama ","112487527");
INSERT INTO hospital VALUES("17","Vijaya Kumarathunga Memorial Hospital","Seeduwa ","0112258862");
INSERT INTO hospital VALUES("18","Rural Hospital","Kapala Kanda ","0112236328");
INSERT INTO hospital VALUES("19","Peripheral Hospital ","Radawana ","0332267261");
INSERT INTO hospital VALUES("20","Peripheral Hospital ","Akkaragama ","0312269261");
INSERT INTO hospital VALUES("21","Peripheral Hospital ","Bokalagama ","332270283");
INSERT INTO hospital VALUES("22","Rural Hospital","Hiripitiya ","0332279261");
INSERT INTO hospital VALUES("41","Rural hospital","Seeduwa","0335685741");
INSERT INTO hospital VALUES("51","Co-operative Hospital","Gampaha","0332222201");
DROP TABLE invoice;
CREATE TABLE `invoice` (
`InvoiceNo` char(50) DEFAULT NULL,
`NIC` varchar(50) DEFAULT NULL,
`Date` date DEFAULT NULL,
`DrugNo` char(50) DEFAULT NULL,
`Qty` int(11) DEFAULT NULL,
`Discount` varchar(50) DEFAULT NULL,
`DiscountedPrice` varchar(50) DEFAULT NULL,
`Method` int(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO invoice VALUES("1701081","935643090v","2017-01-08","1","18","2","100.00","0");
INSERT INTO invoice VALUES("1701081","933560612V","2017-01-08","2","50","1","200.00","1");
INSERT INTO invoice VALUES("1701085","930492515v","2017-01-11","3","10","1","500.00","0");
DROP TABLE news;
CREATE TABLE `news` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`postnews` varchar(500) NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=latin1;
INSERT INTO news VALUES("1","Tommorow we will be closed.","2016-11-02");
INSERT INTO news VALUES("2","Now you can order online your prescribed medicine","2016-11-02");
INSERT INTO news VALUES("3","Now you can buy medicine with 5% discount.","2017-01-10");
INSERT INTO news VALUES("11","There is a vacancy for a pharmacist","2016-05-12");
INSERT INTO news VALUES("12","Tommorow will be opened at 10 am","2017-01-10");
INSERT INTO news VALUES("21","Tommorrow pharmacy will be closed","2017-01-15");
DROP TABLE notifications;
CREATE TABLE `notifications` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Content` varchar(200) NOT NULL DEFAULT '0',
`Title` varchar(50) DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE order;
;
DROP TABLE pharmacist;
CREATE TABLE `pharmacist` (
`NIC` varchar(50) NOT NULL,
`FirstName` varchar(50) NOT NULL,
`LastName` varchar(50) NOT NULL,
`Gender` enum('Male','Female') NOT NULL,
`DOB` date NOT NULL,
`PermanentAddress` varchar(150) NOT NULL,
`CivilStatus` enum('Single','Married','Widowed','Divorced') NOT NULL,
`ContactNo` char(50) NOT NULL,
`EmailAddress` varchar(50) NOT NULL,
`Password` varchar(50) NOT NULL,
`DateHired` date NOT NULL,
`Admin/Trainee` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`NIC`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO pharmacist VALUES("930492515V","Admin","User","Male","1993-12-07","No.13, Main Stret, Gamapaha.","Married","773003002","admin@gmail.com","test123","2016-12-07","1");
DROP TABLE questions;
CREATE TABLE `questions` (
`qId` int(2) NOT NULL,
`question` varchar(500) NOT NULL,
`correctAns` varchar(200) NOT NULL,
`wrongAns1` varchar(200) NOT NULL,
`wrongAns2` varchar(200) NOT NULL,
`wrongAns3` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO questions VALUES("1","Heparin therapy is monitored by which of the following tests?","APTT"," INR","Bleeding time","Serum fibrinogen");
INSERT INTO questions VALUES("2","Which of the following is a common side effect of calcium channel blockers?","Peripheral oedema","Angio-oedema","Headache","Insomnia");
INSERT INTO questions VALUES("3","A 68-years old female presents with a 2-week history of unilateral headache and an ESR 80 mm/hr. The most appropriate treatment is?","Prednisolone
\nPrednisolone","NSAID","Panadol","Insulin");
INSERT INTO questions VALUES("4","A patient, who had been taking a particular drug, now presents with haematuria. The drug is most likely?","Naproxen-NSAID","Calcium channel blocke","Digoxin","Shigella");
INSERT INTO questions VALUES("5","The most common cause of traveller’s diarrhoea is?","Enterotoxic E. Coli","Salmonella Typhi","Shigella","Giardia Lamblia");
INSERT INTO questions VALUES("6","Which of the following is least likely to cause facial nerve palsy?","Chronic parotitis","Parotid tumour","Skull fracture","Mastoiditis");
INSERT INTO questions VALUES("7","The single most reliable test for Haemochromatosis is?","Transferrin saturation","Red cell mass","Serum iron","Serum ferritin");
INSERT INTO questions VALUES("8","Which of the following, is administration of immunoglobin as a prophylaxis not useful?","Hepatitis A","Hepatitis B","Rubella","Mumps");
INSERT INTO questions VALUES("9","Von Willebrandt’s disease you will find:","Increase bleeding time","Cannot find anything","Increased platelet count","Normal APTT");
INSERT INTO questions VALUES("10","The following drugs are proven to decrease the mortality in myocardial infection,","Aspirin","ACE inhibitors","Beta blockers","Nifedipine");
INSERT INTO questions VALUES("11","The following are feature of ROSS RIVER, Except","Chest pain","Muscle pain Davidson-107","Fever","Lathergy");
INSERT INTO questions VALUES("12","Haemochromatosis, WOF will suggest diagnosis?","Serum transferrin","Serum Fe","Serum Ferritin","Iron daturation");
INSERT INTO questions VALUES("13","A 57 yr oldlady develops sudden onset of left sided weakness and right eye blindness.This is most likely due to-","Cerebellar lesion","Vertebro-basilar insufficy","Pituitary tumour","Carotid artery stenosis");
INSERT INTO questions VALUES("14","Another repeated ques. (and confusing as well!!): Which org does not cause lung abscess","P. carinii","M. pneuminiae","M. TB","Staph aureus");
DROP TABLE reportorder;
CREATE TABLE `reportorder` (
`Email` varchar(60) DEFAULT NULL,
`Date` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-12");
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-12");
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-12");
INSERT INTO reportorder VALUES("ab@gmail.com","2017-01-13");
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-13");
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-13");
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-13");
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-14");
INSERT INTO reportorder VALUES("amal@gmail.com","2017-01-14");
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-14");
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-14");
INSERT INTO reportorder VALUES("abc@gmail.com","2017-01-14");
INSERT INTO reportorder VALUES("ab@gmail.com","2017-01-14");
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-14");
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-14");
INSERT INTO reportorder VALUES("ab@gmail.com","2017-01-14");
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-14");
INSERT INTO reportorder VALUES("ab@gmail.com","2017-01-14");
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-15");
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-15");
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-15");
INSERT INTO reportorder VALUES("lasithd2@gmail.com","2017-01-15");
INSERT INTO reportorder VALUES("dhanushka93u@gmail.com","2017-01-15");
DROP TABLE supplier;
CREATE TABLE `supplier` (
`supNo` char(50) NOT NULL,
`Company_Name` varchar(50) NOT NULL,
`Permenant_Address` varchar(100) NOT NULL,
`Contact_No` char(50) NOT NULL,
`Email_Address` varchar(50) NOT NULL,
PRIMARY KEY (`supNo`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO supplier VALUES("01","Hemas Pharmaceuticals","No.75, Sir Baron Jayathilaka Mawatha, Colombo 8","0112320356","Hemas@gmail.com");
INSERT INTO supplier VALUES("02","Glaxo Healthcare (Pvt) Ltd","No. 94, Old Kottawa Road, Nawinna.","0112850229","gl@gmail.com");
INSERT INTO supplier VALUES("03","Meditech ","23, Medtech, Temple road, Gampaha","0332323456","med@gmail.com");
INSERT INTO supplier VALUES("04","Arogya","23 ,Godagama Road, Kalutara","0342345678","Arogya45@gmail.com");
DROP TABLE trainee;
CREATE TABLE `trainee` (
`NIC` varchar(50) NOT NULL,
`FName` varchar(50) NOT NULL,
`LName` varchar(50) NOT NULL,
`Gender` enum('Male','Female') NOT NULL,
`DOB` date NOT NULL,
`PermenentAddr` varchar(150) NOT NULL,
`CivilStatus` enum('Single','Married') NOT NULL,
`ContactNo` char(50) NOT NULL,
`email` varchar(50) NOT NULL,
`Password` varchar(50) NOT NULL,
`DateHired` date NOT NULL,
PRIMARY KEY (`NIC`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO trainee VALUES("923456789V","Anusha","Mendis","Female","1992-11-10","Kandy","Married","772123457","lmn@gmail.com","lmn123","2017-01-01");
INSERT INTO trainee VALUES("935780942V","Geeth","Perera","Male","1993-01-11","Colombo","Single","710598705","asd@gmail.com","gee123","2016-01-11");
INSERT INTO trainee VALUES("946756435V","Ishan","Aoki","Male","1994-01-10","Bandarawela","Single","771234567","xyz@gmail.com","xyz123","2016-01-10");
DROP TABLE vacancy;
CREATE TABLE `vacancy` (
`FullName` text NOT NULL,
`Gender` varchar(10) NOT NULL,
`DOB` date NOT NULL,
`Address` varchar(100) NOT NULL,
`District` tinytext NOT NULL,
`ContactNumber` char(10) NOT NULL,
`NIC` varchar(13) NOT NULL,
`Email` varchar(50) NOT NULL,
`Experience` varchar(10) NOT NULL,
`Information` varchar(255) NOT NULL,
`CV` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
-- phpMyAdmin SQL Dump
-- version 5.1.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Sep 09, 2021 at 06:51 PM
-- Server version: 10.4.20-MariaDB
-- PHP Version: 8.0.9
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `social`
--
-- --------------------------------------------------------
--
-- Table structure for table `like_options`
--
CREATE TABLE `like_options` (
`id` tinyint(2) NOT NULL,
`text` char(5) COLLATE utf8_swedish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci;
--
-- Dumping data for table `like_options`
--
INSERT INTO `like_options` (`id`, `text`) VALUES
(1, 'Like'),
(2, 'Love'),
(3, 'Haha'),
(4, 'Yay'),
(5, 'Wow'),
(6, 'Sad'),
(7, 'Angry');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `like_options`
--
ALTER TABLE `like_options`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `like_options`
--
ALTER TABLE `like_options`
MODIFY `id` tinyint(2) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
create table `live_team` {
`id`
} |
-- Lists all the cities of California thah can be found in
-- database hbtn_0d_usa
SELECT id, name FROM cities WHERE state_id =
(SELECT id FROM states
WHERE name = 'California');
|
delete
from
sbx_temp.fdethybrysdata
where
country||aniocampana||interactionutcdate >= '{date1}'
|
--liquibase formatted sql
--changeset pratik:1 runOnChange:false runAlways:false
ALTER TABLE "gt_src"
ADD COLUMN country_iso character varying(3000),
ADD COLUMN rg_id character varying(3000),
ADD COLUMN rg_parent_id character varying(3000),
ADD COLUMN rg_name character varying(3000),
ADD COLUMN rg_country character varying(3000),
ADD COLUMN rg_state character varying(3000),
ADD COLUMN rg_city character varying(3000),
ADD COLUMN rg_post_code character varying(3000),
ADD COLUMN rg_type character varying(3000),
ADD COLUMN resolved_type character varying(3000),
ADD COLUMN resolved boolean,
ADD COLUMN confidence_level character varying(100);
|
--
-- Clean up the university demo database
--
SET termout ON
prompt Removing sample university database. Please wait ...
SET termout off
SET feedback off
DROP TABLE Department CASCADE CONSTRAINT;
DROP TABLE Faculty CASCADE CONSTRAINT;
DROP TABLE Subject CASCADE CONSTRAINT;
DROP TABLE Class CASCADE CONSTRAINT;
DROP TABLE Student CASCADE CONSTRAINT;
DROP TABLE Enrolled CASCADE CONSTRAINT;
DROP TABLE Marks CASCADE CONSTRAINT; |
UPDATE Languages
SET answered = 1
WHERE id=2 |
USE Conferencias_DB
--Inicia
INSERT INTO Instituicao(nome, pais, morada) VALUES ('Instituicao 1', 'Portugal', 'Rua X')
--Cria Utilizador
INSERT INTO Utilizador(email, nome, nome_instituicao) VALUES('matumbino@email.com', 'Matumbino Chota Grande', 'Instituicao 1')
INSERT INTO Utilizador(email, nome, nome_instituicao) VALUES('tiburcio@email.com', 'Tiburcio Balde', 'Instituicao 1')
SELECT * FROM Utilizador
--Apaga um utilizador que nao esta em uso
DELETE FROM Utilizador WHERE email = 'tiburcio@email.com'
SELECT * FROM Utilizador
--Cria Conferencia
INSERT INTO Conferencia(nome, ano, acronimo, email_presidente, limiteSubArtigo, limiteRevArtigo)
VALUES('Conferencia 1', 2010, 'C1', 'matumbino@email.com', '2010-01-01', '2010-12-01')
--Tentativa de apagar um Utilizador numa Conferencia
DELETE FROM Conferencia WHERE nome = 'Conferencia 1' AND ano = 2010
DELETE FROM Utilizador WHERE email = 'matumbino@email.com'
SELECT * FROM Utilizador
--Finalizacao
DELETE FROM Instituicao WHERE nome = 'Instituicao 1' |
/**
* SQL for searching aza information
* @author HaiTTH
* @version $Id: GetAzaListService_getAzaList_Sel_01.sql 23837 2014-08-28 08:30:35Z p_chan_hai $
*/
SELECT
MA.AZA_CD,
MA.AZA_NM
FROM MA_CM_MA_AZA MA
WHERE MA.TODOFUKEN_CD = /*todofukenCd*/'40'
AND MA.SHIKUGUN_CD = /*shikugunCd*/'215'
AND MA.OOAZA_CD = /*ooazaCd*/'008'
ORDER BY MA.AZA_CD ASC |
copy car_loc from 'dir/carloc.txt' with delimiter ',' null '' csv header;
copy car_state from 'dir/carstate.txt' with delimiter ',' null '' csv header; |
SELECT TB_Turno.TurnoID,
TB_Turno.TurnoNombre,
TB_Turno.Turno
FROM TB_Turno;
|
-- phpMyAdmin SQL Dump
-- version 4.1.14
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: May 04, 2015 at 09:44 PM
-- Server version: 5.6.17
-- PHP Version: 5.5.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `191`
--
-- --------------------------------------------------------
--
-- Table structure for table `fruit`
--
CREATE TABLE IF NOT EXISTS `fruit` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`qty` int(11) NOT NULL,
`dist` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=28 ;
--
-- Dumping data for table `fruit`
--
INSERT INTO `fruit` (`id`, `name`, `qty`, `dist`) VALUES
(1, 'apple', 490, 'green'),
(2, 'pine', 43, 'apple'),
(3, 'ssssssss', 111, 'ssssssss'),
(27, 'pomel', 1234, 'pol');
-- --------------------------------------------------------
--
-- Table structure for table `price`
--
CREATE TABLE IF NOT EXISTS `price` (
`fruit_id` int(11) NOT NULL,
`price` int(11) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
KEY `fk_fruit_id` (`fruit_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
--
-- Dumping data for table `price`
--
INSERT INTO `price` (`fruit_id`, `price`, `date`, `id`) VALUES
(1, 31, '2015-05-03 20:23:04', 1),
(1, 277, '2015-05-03 20:23:04', 2),
(2, 90, '2015-05-03 20:23:16', 3),
(3, 911, '2015-05-03 20:23:16', 4),
(27, 1111, '2015-05-03 14:56:10', 7);
--
-- Constraints for dumped tables
--
--
-- Constraints for table `price`
--
ALTER TABLE `price`
ADD CONSTRAINT `fk_fruit_id` FOREIGN KEY (`fruit_id`) REFERENCES `fruit` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
CREATE TABLE IF NOT EXISTS items (
id SERIAL PRIMARY KEY,
status boolean,
name text
);
|
CREATE DATABASE IF NOT EXISTS `adem` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `adem`;
-- MySQL dump 10.13 Distrib 5.6.13, for Win32 (x86)
--
-- Host: 127.0.0.1 Database: adem
-- ------------------------------------------------------
-- Server version 5.6.14
/*!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 `kullanici`
--
DROP TABLE IF EXISTS `kullanici`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `kullanici` (
`kullanici_id` int(11) NOT NULL AUTO_INCREMENT,
`kullanici_ad` varchar(25) NOT NULL,
`kullanici_soyad` varchar(25) NOT NULL,
`cinsiyet` varchar(1) NOT NULL,
`dogum_tarihi` date NOT NULL,
`sifre` varchar(20) NOT NULL,
`email` varchar(50) DEFAULT NULL,
PRIMARY KEY (`kullanici_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `kullanici`
--
LOCK TABLES `kullanici` WRITE;
/*!40000 ALTER TABLE `kullanici` DISABLE KEYS */;
INSERT INTO `kullanici` VALUES (1,'Mustafa','Yılmaz','E','2014-02-02','3210','mustafa.yilmaz@falan.com'),(2,'Adem','Sen','E','2014-02-02','3210','adem.sen@falan.com'),(3,'Hüsnü','Çoban','E','2014-02-08','456','husnu.coban@falan.com'),(4,'Adem','?engül','E','2013-05-05','adem','masengul@gmail.com'),(5,'faln','filan','E','2013-05-05','adem','masengul@gmail.com');
/*!40000 ALTER TABLE `kullanici` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `musteri`
--
DROP TABLE IF EXISTS `musteri`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `musteri` (
`musteri_id` int(11) NOT NULL AUTO_INCREMENT,
`musteri_ad` varchar(25) NOT NULL,
`musteri_soyad` varchar(25) NOT NULL,
`cinsiyet` varchar(1) NOT NULL,
`dogum_tarihi` date NOT NULL,
`tckn` varchar(11) NOT NULL,
`sifre` varchar(20) NOT NULL,
PRIMARY KEY (`musteri_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `musteri`
--
LOCK TABLES `musteri` WRITE;
/*!40000 ALTER TABLE `musteri` DISABLE KEYS */;
INSERT INTO `musteri` VALUES (1,'Ali','Demir','E','2014-02-02','11111111111','123456'),(2,'Mustafa','Yılmaz','E','2014-02-02','11111111111','3210');
/*!40000 ALTER TABLE `musteri` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `repository`
--
DROP TABLE IF EXISTS `repository`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `repository` (
`repoistory_id` int(11) NOT NULL AUTO_INCREMENT,
`repository_name` varchar(50) NOT NULL,
`repository_path` varchar(255) NOT NULL,
PRIMARY KEY (`repoistory_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `repository`
--
LOCK TABLES `repository` WRITE;
/*!40000 ALTER TABLE `repository` DISABLE KEYS */;
/*!40000 ALTER TABLE `repository` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2014-04-26 19:05:38
|
select distinct session_id,sql_id, sum(10) ASH from v$active_Session_history
where session_id in ( &sid)
group by session_id,sql_id
order by 3 desc
;
select distinct session_id,event, sum(10) ASH from v$active_Session_history
where session_id in ( &sid)
group by session_id,event
order by 3 desc
;
|
/* Formatted on 17/06/2014 18:13:43 (QP5 v5.227.12220.39754) */
CREATE OR REPLACE FORCE VIEW MCRE_OWN.V_MCRES_WRK_TO_CONT_SP_ITF
(
COD_ABI,
COD_AUTORIZZAZIONE,
LINE
)
AS
SELECT --
-- 20121024 AG Creazione vista
-- 20121105 AG Adattamento al nuovo tracciato
-- 20121107 AG Rimossi segni
-- 20121113 AG Aggiunte condizioni in where condition per corretta individuazione fase workflow
-- 20121127 AG Aggiunto filtro per ABI con contesto e filtro su stato 'CO'
-- 20121206 AG Agginti cod_uo_calcolato e cod_od_calcolato
-- 20121217 AG Filtro su tipologia contropartita = 1
-- 20130108 AG Agginto filtro su causale per calcolo esborso posizione
-- 20130523 AP aggiunto nuovo esborso al tracciato
-- 20130529 AP aggiunti campi cod_abi e cod_autorizzazione per flaggatura
-- 20131120 AP disattivazione controllo pratica attiva e aggiunta controllo spese gia contabilizzata
s.cod_abi,
s.cod_autorizzazione,
TO_CHAR (SYSDATE - 1 / 2, 'yyyymmdd') -- id_dper
|| s.cod_abi -- cod_abi
|| SUBSTR (s.cod_ndg, 4) -- cod_ndg
|| RPAD (NVL (p.cod_uo_pratica, ' '), 5, ' ') -- cod_uo_pratica = cod_uo_proponente
|| RPAD (s.cod_autorizzazione, 20, ' ') -- cod_autorizzazione
|| RPAD (NVL (s.cod_autorizzazione_padre, ' '), 20, ' ') -- cod_autorizzazione_padre
|| TO_CHAR (SYSDATE, 'yyyymmdd') -- dta_contabile
|| TO_CHAR (SYSDATE, 'yyyymmdd') -- dta_valuta
|| RPAD (NVL (r.cod_rapporto, ' '), 17, '0') -- cod_rapporto,
|| LPAD (NVL (c.val_importo * 100, 0), 15, '0') -- val_importo_contropartita
|| NVL (s.cod_causale, ' ') -- cod_causale
|| LPAD (NVL (s.val_importo_valore, 0) * 100, 15, '0') -- val_importo_spesa
|| LPAD (NVL (es.val_tot + s.val_importo_valore, 0) * 100, 15, '0') -- val_totale_esborsi_pos
|| NVL (p.flg_gestione, ' ') -- tipo gestione
|| NVL (s.cod_tipo_autorizzazione, ' ') -- cod_tipo_autorizzazione = tipologia spesa
|| RPAD (NVL (p.cod_matr_pratica, ' '), 7, ' ') -- matricola del gestore della pratica legale
|| LPAD (
(NVL (es2.val_tot, 0) + NVL (s.val_importo_valore, 0)) * 100,
15,
'0') -- val_totale_spese
|| RPAD (' ', 80, ' ') -- FILLER
|| RPAD (NVL (s.cod_uo_calcolato, ' '), 5, ' ') -- cod_uo_calcaolato
|| RPAD (NVL (s.cod_od_calcolato, ' '), 2, ' ') -- cod_od_calcolato
--
line
FROM t_mcres_app_spese_itf s,
t_mcres_app_rapporti_itf r,
t_mcres_app_pratiche p,
t_mcres_app_contropartite_itf c,
( -- totale esborso posizione
SELECT cod_abi, cod_ndg, SUM (val_importo_valore) val_tot
FROM t_mcres_app_sp_spese
WHERE 0 = 0 AND cod_stato IN ('CO') AND cod_causale = 'A'
GROUP BY cod_abi, cod_ndg) es,
( -- totale esborso posizione
SELECT cod_abi, cod_ndg, SUM (val_importo_valore) val_tot
FROM t_mcres_app_sp_spese
WHERE 0 = 0 AND cod_stato IN ('CO')
GROUP BY cod_abi, cod_ndg) es2
WHERE 0 = 0
AND s.cod_abi = SYS_CONTEXT ('userenv', 'client_info') -- parametrizzazione per ABI
AND s.cod_autorizzazione = r.cod_autorizzazione(+)
AND s.cod_abi = p.cod_abi
AND s.cod_ndg = p.cod_ndg
AND s.val_anno_pratica = p.val_anno
AND s.cod_pratica = p.cod_pratica
AND s.cod_abi = es.cod_abi(+)
AND s.cod_ndg = es.cod_ndg(+)
-- AP 23/05/2013
AND s.cod_abi = es2.cod_abi(+)
AND s.cod_ndg = es2.cod_ndg(+)
--
AND c.cod_tipo = '1'
--AND p.flg_attiva = 1
AND s.cod_autorizzazione = c.cod_autorizzazione
AND flg_inviata_per_contabil = 0
AND flg_fornitore_non_censito = 0
---
AND s.flg_inviata_per_calc_uo_od = 1
AND s.flg_calcolato_uo_od = 1
AND s.flg_docs_archiviati = 1
AND s.flg_inserita_sp_spese = 1
AND EXISTS
(SELECT 1
FROM t_mcres_app_sp_spese
WHERE 0 = 0
AND cod_stato = 'CO'
AND cod_autorizzazione = s.cod_autorizzazione
AND flg_contabilizzata = 0);
GRANT DELETE, INSERT, REFERENCES, SELECT, UPDATE, ON COMMIT REFRESH, QUERY REWRITE, DEBUG, FLASHBACK, MERGE VIEW ON MCRE_OWN.V_MCRES_WRK_TO_CONT_SP_ITF TO MCRE_USR;
|
create table CHAT_MESSAGE (
MESSAGE_ID number NOT NULL PRIMARY KEY,
NICKNAME VARCHAR2(20) NOT NULL,
REGISTER_DATE DATE NOT NULL,
MESSAGE VARCHAR2(200) NOT NULL
) |
--The Foodie-Fi team wants you to create a new `payments` table for the year 2020 that includes amounts paid by each customer in the `subscriptions` table with the following requirements:
-- monthly payments always occur on the same day of the month as the original `start_date` of any monthly paid plan
-- upgrades from basic to monthly or pro plans are reduced by the current paid amount in that month and start immediately
-- upgrades from pro monthly to pro annual are paid at the end of the current billing period and also starts at the end of the month period
-- once a customer churns they will no longer make payments
SELECT customer_id,DENSE_RANK () OVER (PARTITION BY customer_id ORDER BY start_date) AS order_id,start_date,plan_name,
LEAD (plan_name,1) OVER (PARTITION BY customer_id ORDER BY start_date) AS next_plan,
CASE WHEN plan_name='pro annual' THEN 199
WHEN plan_name='basic monthly' THEN 9.90
WHEN plan_name='pro monthly' THEN 19.90 END AS price
FROM foodie_fi.subscriptions
JOIN foodie_fi.plans
USING (plan_id)
WHERE DATE_PART('year',start_date)=2020 AND plan_name='pro monthly' OR plan_name='basic monthly' OR plan_name='pro annual'
|
-- phpMyAdmin SQL Dump
-- version 4.9.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jan 28, 2021 at 06:11 AM
-- Server version: 10.4.8-MariaDB
-- PHP Version: 7.3.11
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: `chatnode`
--
-- --------------------------------------------------------
--
-- Table structure for table `comments`
--
CREATE TABLE `comments` (
`comment_id` int(100) NOT NULL,
`post_id` varchar(100) NOT NULL,
`user_id` varchar(100) NOT NULL,
`name` varchar(100) NOT NULL,
`content_comment` varchar(100) NOT NULL,
`image` varchar(100) NOT NULL,
`created` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `comments`
--
INSERT INTO `comments` (`comment_id`, `post_id`, `user_id`, `name`, `content_comment`, `image`, `created`) VALUES
(1, '2', '1', 'NB Patil', 'Hi, This is for testing.', 'uploads/profile/NEELAKANTAGOUDAPATIL.png', '1607532805'),
(2, '1', '2', 'Varun Patil', 'Hello', 'uploads/profile/logo-dark.svg', '1607532815'),
(3, '6', '1', 'Neelakanta Gouda Patil', 'Thank full its working.', 'uploads/profile/NEELAKANTAGOUDAPATIL.png', '1610879091'),
(4, '9', '1', 'Neelakanta Gouda Patil', 'Helpful', 'uploads/profile/NEELAKANTAGOUDAPATIL.png', '1611807492');
-- --------------------------------------------------------
--
-- Table structure for table `post`
--
CREATE TABLE `post` (
`post_id` int(100) NOT NULL,
`user_id` varchar(100) NOT NULL,
`post_image` varchar(100) DEFAULT NULL,
`doc_file` varchar(100) DEFAULT NULL,
`content` varchar(100) DEFAULT NULL,
`created` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `post`
--
INSERT INTO `post` (`post_id`, `user_id`, `post_image`, `doc_file`, `content`, `created`) VALUES
(1, '1', 'uploads/pic/map.jpg', NULL, 'Hello World!', '1607532529'),
(2, '2', 'uploads/pic/BigData-thumbnail.png', NULL, 'Big Data', '1607532893'),
(3, '1', 'uploads/pic/Mood board1.jpg', NULL, 'Testing the new changes!', '1609753428'),
(4, '1', 'uploads/pic/dbf5b23592c4347741d6b756c60d6347.jpg', NULL, 'Working good', '1609753698'),
(5, '1', 'uploads/pic/badge.png', NULL, 'Checking the updates', '1610862735'),
(6, '1', 'uploads/pic/black lion live wallpaper HD Photo Wallpaper Collection HD WALLPAPERS.jpg', NULL, 'Checking once again after the changes that I have made!', '1610878991'),
(9, '2', 'uploads/pic/ML-thumbnail.jpg', 'uploads/doc/ML.pdf', 'Machine Learning', '1611765284'),
(10, '1', 'uploads/pic/python1-thumbnail.png', 'uploads/doc/Python Tutorial.pdf', 'Python Tutorial', '1611808026');
-- --------------------------------------------------------
--
-- Table structure for table `transaction`
--
CREATE TABLE `transaction` (
`id` int(100) NOT NULL,
`from_id` int(100) NOT NULL,
`to_id` int(100) NOT NULL,
`post_id` int(100) NOT NULL,
`timestamp` varchar(255) NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `transaction`
--
INSERT INTO `transaction` (`id`, `from_id`, `to_id`, `post_id`, `timestamp`) VALUES
(1, 1, 2, 9, '2021-01-28 00:04:13');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`user_id` int(100) NOT NULL,
`firstname` varchar(100) NOT NULL,
`lastname` varchar(100) NOT NULL,
`username` varchar(100) NOT NULL,
`birthday` varchar(100) NOT NULL,
`gender` varchar(100) NOT NULL,
`number` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`profile_picture` varchar(100) DEFAULT NULL,
`credits` int(100) NOT NULL DEFAULT 10
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`user_id`, `firstname`, `lastname`, `username`, `birthday`, `gender`, `number`, `email`, `password`, `profile_picture`, `credits`) VALUES
(1, 'Neelakanta Gouda', 'Patil', 'nbpatil', '1999-11-01', 'Male', '6365254140', 'patil@example.com', 'b813a1b1181d720d0fbad61a0ac27ed9', 'uploads/profile/NEELAKANTAGOUDAPATIL.png', 9),
(2, 'Varun', 'Patil', 'varun', '2012-06-20', 'Male', '6365254141', 'varun@example.com', '7d5a71f538ad2d041eccf37b2d5b3772', 'uploads/profile/logo-dark.svg', 11),
(3, 'KEERTHI', 'M R', 'lkeerthi', '1998-09-14', 'Male', '9066421048', 'keerthikitty1998@gmail.com', '9f7c6177c5e664e6a9122a9c1c8108cc', 'uploads/profile/DSC03559.JPG', 10),
(6, 'Ganesh', 'v', 'gani', '1999-10-12', 'Male', '9066421648', 'something@gmail.com', '1a1dc91c907325c69271ddf0c944bc72', 'uploads/profile/user.jpg', 10);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `comments`
--
ALTER TABLE `comments`
ADD PRIMARY KEY (`comment_id`);
--
-- Indexes for table `post`
--
ALTER TABLE `post`
ADD PRIMARY KEY (`post_id`);
--
-- Indexes for table `transaction`
--
ALTER TABLE `transaction`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`user_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `comments`
--
ALTER TABLE `comments`
MODIFY `comment_id` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `post`
--
ALTER TABLE `post`
MODIFY `post_id` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT for table `transaction`
--
ALTER TABLE `transaction`
MODIFY `id` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `user_id` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
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 */;
|
/*
Warnings:
- You are about to drop the `_PictureToProject` table. If the table is not empty, all the data it contains will be lost.
- Added the required column `postId` to the `Picture` table without a default value. This is not possible if the table is not empty.
- Added the required column `projectId` to the `Picture` table without a default value. This is not possible if the table is not empty.
*/
-- DropForeignKey
ALTER TABLE "_PictureToProject" DROP CONSTRAINT "_PictureToProject_A_fkey";
-- DropForeignKey
ALTER TABLE "_PictureToProject" DROP CONSTRAINT "_PictureToProject_B_fkey";
-- AlterTable
ALTER TABLE "Picture" ADD COLUMN "postId" INTEGER NOT NULL,
ADD COLUMN "projectId" INTEGER NOT NULL;
-- DropTable
DROP TABLE "_PictureToProject";
-- AddForeignKey
ALTER TABLE "Picture" ADD FOREIGN KEY ("projectId") REFERENCES "Project"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
-- phpMyAdmin SQL Dump
-- version 5.0.1
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Feb 03, 2020 at 10:29 PM
-- Server version: 10.4.11-MariaDB
-- PHP Version: 7.4.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 */;
--
-- Database: `kdBasisGames`
--
-- --------------------------------------------------------
--
-- Table structure for table `leaderboard`
--
CREATE TABLE `leaderboard` (
`nickname` text NOT NULL,
`time` int(11) NOT NULL,
`score` text NOT NULL,
`date` timestamp NOT NULL DEFAULT current_timestamp(),
`game` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
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 */; |
set serveroutput on;
create or replace trigger on_student_quantity_change
after delete or update or insert on students
for each row
declare
tmp number;
pragma autonomous_transaction;
begin
case
when inserting then
select c_val into tmp from groups where id = :new.group_id;
update groups set c_val = tmp + 1 where id = :new.group_id;
when deleting then
select c_val into tmp from groups where id = :old.group_id;
update groups set c_val = tmp - 1 where id = :old.group_id;
when updating then
if :new.group_id != :old.group_id then
select c_val into tmp from groups where id = :old.group_id;
update groups set c_val = tmp - 1 where id = :old.group_id;
select c_val into tmp from groups where id = :new.group_id;
update groups set c_val = tmp + 1 where id = :new.group_id;
end if;
end case;
commit;
exception
when no_data_found then
dbms_output.put_line('group with such id does not exists');
end; |
CREATE PROC [ERP].[Usp_Del_Concepto]
@ID INT
AS
BEGIN
DELETE FROM [ERP].[Concepto] WHERE ID = @ID
END
|
// use this script only when project fails to auto update
CREATE DATABASE IF NOT EXISTS `weather_map`;
USE `weather_map`;
--
-- Table structure for table `user`
--
DROP TABLE IF EXISTS `user_details`;
CREATE TABLE user_details(
username VARCHAR(30) NOT NULL,
pass VARCHAR(50) NOT NULL,
date_of_birth VARCHAR(50) NOT NULL
); |
CREATE DATABASE `estore`;
USE `estore`;
DROP TABLE `estore`.`users`;
DROP TABLE `estore`.`products`;
DROP TABLE `estore`.`prices`;
DROP TABLE `estore`.`inentory`;
DROP TABLE `estore`.`selections`;
DROP TABLE `estore`.`carts`;
DROP TABLE `estore`.`transactions`;
CREATE TABLE `estore`.`users` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(32) NULL,
`last_name` VARCHAR(32) NULL,
`username` VARCHAR(32) NOT NULL UNIQUE,
`password` VARCHAR(32) NULL,
`login_token` VARCHAR(512) NULL,
PRIMARY KEY (id),
INDEX (username)
) ENGINE=INNODB;
INSERT INTO `estore`.`users` (id,first_name, last_name, username, password) VALUES (1, 'douglas', 'ahlquist', 'dahlquist', ' password');
CREATE TABLE `estore`.`products` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`category` VARCHAR(32) NOT NULL,
`description` VARCHAR(200) NOT NULL,
`image_url` VARCHAR(512) NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE `estore`.`variation` (
`id` VARCHAR(64) NOT NULL UNIQUE,
`product_id` BIGINT(20) NOT NULL,
`attributes` JSON NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (product_id) REFERENCES `estore`.`products` (id)
) ENGINE=INNODB;
CREATE TABLE `estore`.`prices` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`product_id` BIGINT(20) NOT NULL,
`variation_id` VARCHAR(64) NULL,
`start_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`end_time` TIMESTAMP NOT NULL,
`amount` DECIMAL(6,2) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (product_id) REFERENCES `estore`.`products` (id),
FOREIGN KEY (variation_id) REFERENCES `estore`.`variation` (id)
) ENGINE=INNODB;
CREATE TABLE `estore`.`inventory` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`product_id` BIGINT(20) NOT NULL,
`variation_id` VARCHAR(64) NULL,
`count` INT,
PRIMARY KEY (id),
FOREIGN KEY (product_id) REFERENCES `estore`.`products` (id),
FOREIGN KEY (variation_id) REFERENCES `estore`.`variation` (id)
) ENGINE=INNODB;
CREATE TABLE `estore`.`selections` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`user_id` BIGINT(20) NOT NULL,
`product_id` BIGINT(20) NOT NULL,
`variation_id` VARCHAR(64) NOT NULL,
`count` INT,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES `estore`.`users` (id),
FOREIGN KEY (product_id) REFERENCES `estore`.`products` (id),
FOREIGN KEY (variation_id) REFERENCES `estore`.`variation` (id)
) ENGINE=INNODB;
CREATE TABLE `estore`.`carts` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`user_id` BIGINT(20) NOT NULL,
`open_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES `estore`.`users` (id)
) ENGINE=INNODB;
CREATE TABLE `estore`.`transactions` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`type` VARCHAR(1) NOT NULL,
`user_id` BIGINT(20) NOT NULL,
`payment_info` JSON NOT NULL,
`product_info` JSON NOT NULL,
`cost` DECIMAL(6,2),
`trnsaction_time` timestamp NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES `estore`.`users` (id)
) ENGINE=INNODB;
CREATE VIEW `estore`.`productinventoryprice` AS
SELECT
pd.id AS id,
pd.category AS category,
pd.description AS description,
pd.image_url AS image_url,
v.id AS variation_uuid,
v.attributes AS attributes,
pc.start_time AS sale_start_time,
pc.end_time AS sale_end_time,
pc.amount AS amount,
i.count AS count
FROM products pd
JOIN prices pc ON pd.id = pc.product_id
JOIN inventory i ON pd.id = i.product_id
JOIN variation v ON pd.id = v.product_id;
|
CREATE DATABASE mydb DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
CREATE USER django@'%' IDENTIFIED BY 'assword';
GRANT ALL PRIVILEGES ON mydb.* TO django@'%';
FLUSH PRIVILEGES;
|
--Operador +
SELECT 1 + 3
--Operador *
SELECT 3 * 2
--Operador -
SELECT 5 - 2
--Operador -
SELECT 5 - 2
--Operador /
SELECT 15 / 3
--Operador %
SELECT 15 % 5
--Combinando operadores
SELECT ((1 + 4) * (3 * 3)) / 5 |
INSERT INTO vpbx.syncparam(name, key, enabled) VALUES ('vpbx.autolink_ip', 'id', true);
CREATE TRIGGER tr_autolink_ip
AFTER INSERT OR UPDATE OR DELETE
ON vpbx.autolink_ip
FOR EACH ROW
EXECUTE PROCEDURE event.notify_table_upd();
|
drop table if exists relationships;
drop table if exists persons cascade;
create table persons (
id serial primary key,
first_name varchar(60),
nick_name varchar(60),
middle_name varchar(60),
last_name varchar(120) not null,
last_name_alias varchar(120),
gender varchar(1) not null,
birth_city varchar(120),
birth_state varchar(2),
born date,
died date,
bio varchar
);
create table relationships (
id serial primary key,
parent_id int4 not null references persons(id) on delete cascade,
child_id int4 not null references persons(id) on delete cascade,
relationship_desc varchar(20),
relationship_begin_date date,
relationship_end_date date
);
alter table persons add constraint persons_uniq unique (first_name, last_name, birth_city, birth_state, born);
alter table relationships add constraint relationships_uniq unique (parent_id,child_id,relationship_desc);
|
alter table REPORT_TEMPLATE add IS_GROOVY char(1)^
update REPORT_TEMPLATE set IS_GROOVY = 0 where IS_GROOVY is null^ |
sqlplus system/1234
alter user hr identified by hr account unlock;
conn hr/hr
sqlplus hr/hr
select * from tab;
select * from employees;
**************
* TABLESPACE *
***************
create TABLESPACE mc
datafile 'C:\oraclexe\app\oracle\oradata\XE\mc.dbf'
size 10M
autoextend on next 1M maxsize UNLIMITED;
drop TABLESPACE mc INCLUDING CONTENTS AND Dafatiles;
******************
* CREATE ACCOUNT *
******************
관리자모드에서
test01이라는 계정 생성, 비밀번호는 1234
기본적으로 mc라는 이름의 tablespace는 mc입니당
create user test01 identified by 1234
default TABLESPACE mc;
권한부여 dba : 관리자권한
grant connect,resource,dba to test01;
sqlplus test01/1234
권한뺏기
revoke dba from test01;
삭제
drop user test01 cascade;
test01 테이블을 삭제
**********************
* SCOTT/TIGER 계정 생성 *
**********************
create user SCOTT identified by TIGER
default TABLESPACE mc;
@c:lib/scott.sql;
@실행 : sql파일에 있는거 모두 실행
어느 창에서 실행하든 상관 없음
select * from tab;
set linesize 300;
임의의 폭 값 설정
set pagesize 200;
(1회용임)
select * from emp;
emp테이블에 있는 column 다 보여줘 |
-- phpMyAdmin SQL Dump
-- version 4.4.10
-- http://www.phpmyadmin.net
--
-- Client : localhost:8889
-- Généré le : Mer 31 Août 2016 à 16:11
-- Version du serveur : 5.5.42
-- Version de PHP : 7.0.0
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de données : `the_hunt`
--
-- --------------------------------------------------------
--
-- Structure de la table `game`
--
CREATE TABLE `game` (
`id_game` int(10) unsigned NOT NULL,
`score_tracker` tinyint(50) NOT NULL,
`score_target` tinyint(10) NOT NULL,
`credit_tracker` tinyint(50) NOT NULL,
`credit_target` tinyint(4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Structure de la table `player`
--
CREATE TABLE `player` (
`id_user` mediumint(8) unsigned NOT NULL,
`id_game` int(10) unsigned NOT NULL,
`tracker` tinyint(1) NOT NULL,
`latitude` int(11) NOT NULL,
`longitude` int(11) NOT NULL,
`code` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Structure de la table `user`
--
CREATE TABLE `user` (
`id_user` mediumint(8) unsigned NOT NULL,
`pseudo` varchar(30) NOT NULL,
`mail` varchar(50) NOT NULL,
`pass` varchar(30) NOT NULL,
`picture` varchar(100) DEFAULT NULL,
`gender` varchar(20) DEFAULT NULL,
`birthdate` date DEFAULT NULL,
`corpulence` varchar(20) DEFAULT NULL,
`hair` varchar(20) DEFAULT NULL,
`eyes` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Index pour les tables exportées
--
--
-- Index pour la table `game`
--
ALTER TABLE `game`
ADD PRIMARY KEY (`id_game`);
--
-- Index pour la table `player`
--
ALTER TABLE `player`
ADD PRIMARY KEY (`id_user`,`id_game`),
ADD UNIQUE KEY `code_player` (`code`);
--
-- Index pour la table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id_user`),
ADD UNIQUE KEY `pseudo` (`pseudo`),
ADD UNIQUE KEY `mail` (`mail`),
ADD KEY `gender` (`gender`),
ADD KEY `corpulence` (`corpulence`),
ADD KEY `hair` (`hair`),
ADD KEY `eyes` (`eyes`);
--
-- AUTO_INCREMENT pour les tables exportées
--
--
-- AUTO_INCREMENT pour la table `game`
--
ALTER TABLE `game`
MODIFY `id_game` int(10) unsigned NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `user`
--
ALTER TABLE `user`
MODIFY `id_user` mediumint(8) unsigned NOT NULL AUTO_INCREMENT;
/*!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 oauth_token (
instance_id text NOT NULL,
component_id text NOT NULL,
access_token text NOT NULL,
refresh_token text,
token_type text,
expires timestamp,
provider text NOT NULL,
created timestamp NOT NULL,
PRIMARY KEY (instance_id, component_id)
);
CREATE TABLE widget_settings (
instance_id text NOT NULL,
component_id text NOT NULL,
settings json DEFAULT '{}',
service_settings json DEFAULT '{}',
curr_provider text,
user_profile json DEFAULT '{}',
updated timestamp NOT NULL,
created timestamp NOT NULL,
PRIMARY KEY (instance_id, component_id)
);
CREATE TABLE session (
session_id bigserial PRIMARY KEY,
instance_id text NOT NULL,
component_id text NOT NULL,
closed boolean NOT NULL DEFAULT false,
created timestamp NOT NULL
)
CREATE TABLE file (
file_id bigserial PRIMARY KEY,
session_id bigint REFERENCES session ON DELETE RESTRICT,
temp_name text NOT NULL,
original_name text NOT NULL,
size bigint NOT NULL,
created timestamp NOT NULL
);
CREATE TABLE upload_failure (
file_id bigint PRIMARY KEY REFERENCES file ON DELETE CASCADE,
resolved boolean NOT NULL DEFAULT false
);
|
\W
use hackerrank;
select if (g.grade < 8, null, s.name) `name`, g.grade, s.marks
from
students s
inner join grades g
on s.marks between g.min_mark and g.max_mark
order by grade desc, name, marks
;
|
CREATE PROCEDURE PROC_ESPECIALIDADE_I(@ID INTEGER, @NOME VARCHAR)
AS
BEGIN
INSERT INTO ESPECIALIDADE_TB(ID, NOME)
VALUES(@ID, @NOME);
PRINT 'INCLUIDO COM SUCESSO'
END;
EXEC PROC_ESPECIALIDADE_I @ID = 5, @NOME = 'PSIQUIATRA'
CREATE PROCEDURE PROC_ESPECIALIDADE_U(@ID INTEGER, @NOME VARCHAR)
AS
IF @ID != NULL
BEGIN
UPDATE ESPECIALIDADE_TB
SET NOME = @NOME
WHERE ID = @ID
PRINT 'ALTERADO COM SUCESSO'
END;
ELSE
BEGIN
PRINT 'ERRO FATAL'
END
END
EXEC PROC_ESPECIALIDADE_U
CREATE PROCEDURE PROC_ESPECIALIDADE_S
AS
BEGIN
SELECT * FROM ESPECIALIDADE_TB
END
EXEC PROC_ESPECIALIDADE_S
|
-- phpMyAdmin SQL Dump
-- version 4.1.14
-- http://www.phpmyadmin.net
--
-- Client : 127.0.0.1
-- Généré le : Lun 09 Février 2015 à 15:09
-- Version du serveur : 5.6.17
-- Version de PHP : 5.5.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Base de données : `game`
--
-- --------------------------------------------------------
--
-- Structure de la table `data`
--
CREATE TABLE IF NOT EXISTS `data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`caserne_lvl1_z_b` int(11) NOT NULL,
`caserne_lvl1_z_ao` int(11) NOT NULL,
`caserne_lvl1_z_e` int(11) NOT NULL,
`caserne_lvl1_z_c` int(11) NOT NULL,
`caserne_lvl1_vit` int(11) NOT NULL,
`caserne_lvl2_z_b` int(11) NOT NULL,
`caserne_lvl2_z_ao` int(11) NOT NULL,
`caserne_lvl2_z_e` int(11) NOT NULL,
`caserne_lvl2_z_c` int(11) NOT NULL,
`caserne_lvl3_z_b` int(11) NOT NULL,
`caserne_lvl3_z_ao` int(11) NOT NULL,
`caserne_lvl3_z_e` int(11) NOT NULL,
`caserne_lvl3_z_c` int(11) NOT NULL,
`caserne_lvl4_z_b` int(11) NOT NULL,
`caserne_lvl4_z_ao` int(11) NOT NULL,
`caserne_lvl4_z_e` int(11) NOT NULL,
`caserne_lvl4_z_c` int(11) NOT NULL,
`caserne_lvl5_z_b` int(11) NOT NULL,
`caserne_lvl5_z_ao` int(11) NOT NULL,
`caserne_lvl5_z_e` int(11) NOT NULL,
`caserne_lvl5_z_c` int(11) NOT NULL,
`usine_lvl1_z_b` int(11) NOT NULL,
`usine_lvl1_z_ao` int(11) NOT NULL,
`usine_lvl1_z_e` int(11) NOT NULL,
`usine_lvl1_z_c` int(11) NOT NULL,
`usine_lvl2_z_b` int(11) NOT NULL,
`usine_lvl2_z_ao` int(11) NOT NULL,
`usine_lvl2_z_e` int(11) NOT NULL,
`usine_lvl2_z_c` int(11) NOT NULL,
`usine_lvl3_z_b` int(11) NOT NULL,
`usine_lvl3_z_ao` int(11) NOT NULL,
`usine_lvl3_z_e` int(11) NOT NULL,
`usine_lvl3_z_c` int(11) NOT NULL,
`usine_lvl4_z_b` int(11) NOT NULL,
`usine_lvl4_z_ao` int(11) NOT NULL,
`usine_lvl4_z_e` int(11) NOT NULL,
`usine_lvl4_z_c` int(11) NOT NULL,
`usine_lvl5_z_b` int(11) NOT NULL,
`usine_lvl5_z_ao` int(11) NOT NULL,
`usine_lvl5_z_e` int(11) NOT NULL,
`usine_lvl5_z_c` int(11) NOT NULL,
`desosseur_lvl1_z_b` int(11) NOT NULL,
`desosseur_lvl1_z_ao` int(11) NOT NULL,
`desosseur_lvl1_z_e` int(11) NOT NULL,
`desosseur_lvl1_z_c` int(11) NOT NULL,
`desosseur_lvl2_z_b` int(11) NOT NULL,
`desosseur_lvl2_z_ao` int(11) NOT NULL,
`desosseur_lvl2_z_e` int(11) NOT NULL,
`desosseur_lvl2_z_c` int(11) NOT NULL,
`desosseur_lvl3_z_b` int(11) NOT NULL,
`desosseur_lvl3_z_ao` int(11) NOT NULL,
`desosseur_lvl3_z_e` int(11) NOT NULL,
`desosseur_lvl3_z_c` int(11) NOT NULL,
`desosseur_lvl4_z_b` int(11) NOT NULL,
`desosseur_lvl4_z_ao` int(11) NOT NULL,
`desosseur_lvl4_z_e` int(11) NOT NULL,
`desosseur_lvl4_z_c` int(11) NOT NULL,
`desosseur_lvl5_z_b` int(11) NOT NULL,
`desosseur_lvl5_z_ao` int(11) NOT NULL,
`desosseur_lvl5_z_e` int(11) NOT NULL,
`desosseur_lvl5_z_c` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Structure de la table `data_0`
--
CREATE TABLE IF NOT EXISTS `data_0` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`caserne_lvl1_z_b` int(11) NOT NULL,
`caserne_lvl1_vit` int(11) NOT NULL,
`abattoir_lvl1_mdv` int(11) NOT NULL,
`z_b_lvl1_mdv` int(11) NOT NULL,
`z_b_lvl1_att` int(11) NOT NULL,
`z_b_lvl1_def` int(11) NOT NULL,
`z_b_lvl1_pv` int(11) NOT NULL,
`z_b_lvl1_vit` int(11) NOT NULL,
`z_b_lvl1_mov` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Contenu de la table `data_0`
--
INSERT INTO `data_0` (`id`, `caserne_lvl1_z_b`, `caserne_lvl1_vit`, `abattoir_lvl1_mdv`, `z_b_lvl1_mdv`, `z_b_lvl1_att`, `z_b_lvl1_def`, `z_b_lvl1_pv`, `z_b_lvl1_vit`, `z_b_lvl1_mov`) VALUES
(1, 10, 10, 10, 10, 10, 1, 100, 10, 10);
-- --------------------------------------------------------
--
-- Structure de la table `ressources`
--
CREATE TABLE IF NOT EXISTS `ressources` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`r_humain` int(11) NOT NULL,
`r_meat` int(11) NOT NULL,
`r_os` int(11) NOT NULL,
`r_bile` int(11) NOT NULL,
`b_crypt` int(11) NOT NULL,
`b_labo` int(11) NOT NULL,
`b_abattoire` int(11) NOT NULL,
`b_desosseur` int(11) NOT NULL,
`b_usine` int(11) NOT NULL,
`z_basique` int(11) NOT NULL,
`z_enos` int(11) NOT NULL,
`z_explosif` int(11) NOT NULL,
`z_cracheur` int(11) NOT NULL,
`z_mastodonte` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Contenu de la table `ressources`
--
INSERT INTO `ressources` (`id`, `r_humain`, `r_meat`, `r_os`, `r_bile`, `b_crypt`, `b_labo`, `b_abattoire`, `b_desosseur`, `b_usine`, `z_basique`, `z_enos`, `z_explosif`, `z_cracheur`, `z_mastodonte`) VALUES
(1, 0, 100, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(2, 0, 100, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0);
-- --------------------------------------------------------
--
-- Structure de la table `userdata`
--
CREATE TABLE IF NOT EXISTS `userdata` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`nom` varchar(30) NOT NULL,
`email` varchar(30) NOT NULL,
`password` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Contenu de la table `userdata`
--
INSERT INTO `userdata` (`id`, `nom`, `email`, `password`) VALUES
(1, 'thomas', 'good@rzie', 'osef'),
(2, 'levani', 'kvali@shvili', 'osef');
/*!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 */;
|
select
fr.id,
ri.caption,
fr.right_id,
fr.role_id,
ri.is_active,
ri.entity_access_level
from sec_role_right as fr
join sec_right as ri on ri.id=fr.right_id |
CREATE USER 'kanbanuser'@'localhost' identified BY 'kanbanuser';
GRANT ALL privileges ON * . * TO 'kanbanuser'@'localhost';
ALTER USER 'kanbanuser'@'localhost' IDENTIFIED WITH mysql_native_password BY 'kanbanuser'; |
Задания на БД vk:
/*1. Проанализировать какие запросы могут выполняться наиболее часто в процессе работы приложения и добавить необходимые индексы.*/
-- Дабавим индекс из урока
CREATE INDEX media_user_id_media_type_id_idx ON media (user_id, media_type_id);
-- часто просматривают друзей пользователя, добавляем два индекса
CREATE INDEX friendship_user_id_friend_id_idx ON media (user_id, friend_id);
CREATE INDEX friendship_friend_id_user_id_idx ON media (friend_id, user_id);
-- Лайкуют много, и люди любят просматривать кто-что лайкнул
CREATE INDEX likes_user_id_target_id_like_type_id_idx ON media (user_id, target_id, like_type_id);
-- Сообщений всегда очень много. Вся история переписки с другом заслуживает индекса.
CREATE INDEX messages_from_user_id_to_user_id_created_at_idx ON media (from_user_id, to_user_id, created_at);
CREATE INDEX messages_to_user_id_from_user_id_created_at_idx ON media (to_user_id, from_user_id, created_at);
-- Пользователи ищут слова по все переписке, хочется добавить индекс на поле body.
-- Однако это будет не хорошо, слишком большое поле.
-- Нужно будет искать другие решения для ускорения выборки по телу сообщения
-- Возможно имело бы смысл поставить индексы на: город+пользователь, город+пол, на fullname и т.д. но, без статистики такие решения лучше не принимать.
/*2. Задание на денормализацию
Разобраться как построен и работает следующий запрос:
SELECT SUM(count) as overall FROM (
SELECT
CONCAT(u.firstname, ' ', u.lastname) as user,
count(l.id) as count,
TIMESTAMPDIFF(YEAR, p.birthday, NOW()) AS age
FROM users AS u
INNER JOIN profiles AS p
ON p.user_id = u.id
LEFT JOIN media as m
ON m.user_id = u.id
LEFT JOIN messages as t
ON t.from_user_id = u.id
LEFT JOIN likes AS l
ON l.item_id = u.id
AND l.like_type_id = 2
OR l.item_id = m.id AND l.like_type_id = 1
OR l.item_id = t.id AND l.like_type_id = 3
GROUP BY u.id
ORDER BY p.birthday DESC
LIMIT 10) AS likes;
Правильно-ли он построен?
Какие изменения, включая денормализацию, можно внести в структуру БД
чтобы существенно повысить скорость работы этого запроса?*/
-- Запрос выводит сумму лайков у 10 самых молодых пользователей
-- Перенесём подзапрос для удобства в конструкцию with и уберем лишнее из select
-- Что бы не было путаницы поменяем alias у табли и стобцов
WITH rate_likes as (
SELECT
count(l.id) as rate
FROM users AS u
INNER JOIN profiles AS p
ON p.user_id = u.id
LEFT JOIN media as m
ON m.user_id = u.id
LEFT JOIN messages as t
ON t.from_user_id = u.id
LEFT JOIN likes AS l
ON l.item_id = u.id
AND l.like_type_id = 2
OR l.item_id = m.id AND l.like_type_id = 1
OR l.item_id = t.id AND l.like_type_id = 3
GROUP BY u.id
ORDER BY p.birthday DESC
LIMIT 10
)
SELECT SUM(rate) as overall FROM rate_likes;
-- Т.к. мы работает с id пользователя и его днем рождения, то можно делать выборку сразу из таблицы profiles
WITH rate_likes as (
SELECT
count(l.id) as rate
FROM profiles AS p
LEFT JOIN media as m
ON m.user_id = p.user_id
LEFT JOIN messages as t
ON t.from_user_id = p.user_id
LEFT JOIN likes AS l ON
l.item_id = p.user_id AND l.like_type_id = 2
OR l.item_id = m.id AND l.like_type_id = 1
OR l.item_id = t.id AND l.like_type_id = 3
GROUP BY p.user_id
ORDER BY p.birthday DESC
LIMIT 10
)
SELECT SUM(rate) as overall FROM rate_likes;
-- Можно добавить индекс на (likes.item_id , likes.like_type_id), что ускорит выборку
CREATE INDEX rate_likes_item_id_like_type_id) ON (item_id, like_type_id);
-- Если это не помогает, тогда имеет смысл денормализовать таблицу лайков.
CREATE TABLE message_likes (
messages_id INT,
from_user_id INT,
PRIMARY KEY (messages_id, from_user_id)
);
CREATE TABLE user_likes (
to_user_id INT,
from_user_id INT,
PRIMARY KEY (to_user_id, from_user_id)
);
CREATE TABLE media_likes (
media_id INT,
from_user_id INT,
PRIMARY KEY (media_id, from_user_id)
);
START TRANSACTION;
INSERT INTO media_likes (media_id, from_user_id) SELECT item_id, user_id FROM likes WHERE like_type_id = 1;
INSERT INTO user_likes (to_user_id, from_user_id) SELECT item_id, user_id FROM likes WHERE like_type_id = 2;
INSERT INTO message_likes (messages_id, from_user_id) SELECT item_id, user_id FROM likes WHERE like_type_id = 3;
DROP TABLE likes;
DROP TABLE like_types;
COMMIT; |
ALTER VIEW VT_ValorizacionInventarioContable
as
SELECT *
FROM (
SELECT
A.ProductoID,
A.FichaID,
A.Item,
B.FechaID,
A.Orden,
A.DocumentoID,
A.DocumentoItem,
isnull(D.Cantidad, 0) AS Cantidad,
A.TipoID,
C.Tipo,
'Ingreso' AS Movimiento,
B.FundoID,
CASE WHEN B.FundoID = '03'
THEN A.Cantidad
ELSE 0 END AS SR_E_Cantidad,
CASE WHEN B.FundoID = '03' THEN
CASE WHEN A.TipoID IN ('01','02') AND A.DocumentoID IS NOT NULL THEN
CASE WHEN E.MonedaID = '01'
THEN isnull(D.PrecioUnitario,0) - iif(D.AfectoIGV=1,(D.ImporteConIGV-D.Exonerado1)*(G.IGV/(1+G.IGV)),0)/isnull(D.Cantidad,0)*isnull(H.Factor,1)
ELSE (isnull(D.PrecioUnitario,0) - iif(D.AfectoIGV=1,(D.ImporteConIGV-D.Exonerado1)*(G.IGV/(1+G.IGV)),0)/isnull(D.Cantidad,0)*isnull(H.Factor,1)) * isnull(F.TipoCambio, 0) END
ELSE iif(A.AfectoIGV=1,A.Precio*(G.IGV/(1+G.IGV)),A.Precio) END
ELSE 0 END AS SR_E_Precio,
CASE WHEN B.FundoID = '04' AND A.TipoID = '03'
THEN A.Cantidad
ELSE 0 END AS SR_S_Cantidad,
0 AS SR_S_Precio,
CASE WHEN B.FundoID = '04'
THEN A.Cantidad
ELSE 0 END AS SJ_E_Cantidad,
CASE WHEN B.FundoID = '04' THEN
CASE WHEN A.TipoID IN ('01','02') AND A.DocumentoID IS NOT NULL THEN
CASE WHEN E.MonedaID = '01' THEN
isnull(D.PrecioUnitario,0) - iif(D.AfectoIGV=1,(D.ImporteConIGV-D.Exonerado1)*(G.IGV/(1+G.IGV)),0)/isnull(D.Cantidad,0)*isnull(H.Factor,1)
ELSE (isnull(D.PrecioUnitario,0) - iif(D.AfectoIGV=1,(D.ImporteConIGV-D.Exonerado1)*(G.IGV/(1+G.IGV)),0)/isnull(D.Cantidad,0)*isnull(H.Factor,1)) * isnull(F.TipoCambio, 0) END
ELSE iif(A.AfectoIGV=1,A.Precio*(G.IGV/(1+G.IGV)),A.Precio) END
ELSE 0 END AS SJ_E_Precio,
CASE WHEN B.FundoID = '03' AND A.TipoID = '03'
THEN A.Cantidad
ELSE 0 END AS SJ_S_Cantidad,
0 AS SJ_S_Precio,
A.ProductoID VigenteID,
'01' FuenteID
FROM TB_IngresoInventarioDetalle A
LEFT JOIN TB_IngresoInventario B ON A.FichaID = B.FichaID
LEFT JOIN TB_IngresoInventarioTipo C ON A.TipoID = C.TipoID
LEFT JOIN TB_CompraDetalle D ON A.DocumentoID = D.DocumentoID
AND A.DocumentoItem = D.Item
LEFT JOIN TB_Compra E ON D.DocumentoID = E.DocumentoID
LEFT JOIN TB_TipoCambio F ON E.FechaEmisionID = F.FechaID
LEFT JOIN TB_IGV G ON E.FechaEmisionID BETWEEN G.FechaInicioID AND G.FechaFinID
LEFT JOIN TB_InventarioFactor H ON E.Periodo=H.PeriodoID
UNION ALL
SELECT
A.ProductoID,
A.FichaID,
A.Item,
B.FechaID,
A.Orden,
'' AS DocumentoID,
'' AS DocumentoItem,
0 AS Cantidad,
A.TipoID,
C.Tipo,
'Salida' AS Movimiento,
B.FundoID,
0 AS SR_E_Cantidad,
0 AS SR_E_Precio,
CASE WHEN B.FundoID = '03'
THEN A.Cantidad
ELSE 0 END AS SR_S_Cantidad,
0 AS SR_S_Precio,
0 AS SJ_E_Cantidad,
0 AS SJ_E_Precio,
CASE WHEN B.FundoID = '04'
THEN A.Cantidad
ELSE 0 END AS SJ_S_Cantidad,
0 AS SJ_S_Precio,
A.ProductoID VigenteID,
'02' FuenteID
FROM TB_SalidaInventarioDetalle A
LEFT JOIN TB_SalidaInventario B ON A.FichaID = b.FichaID
LEFT JOIN TB_SalidaInventarioTipo C ON A.TipoID = C.TipoID
--WHERE A.TipoID NOT IN ('06')
UNION ALL
SELECT
G.ProductoID,
A.FichaID,
A.Item,
B.FechaID,
A.Orden,
'' AS DocumentoID,
'' AS DocumentoItem,
0 AS Cantidad,
A.TipoID,
C.Tipo,
'Ingreso' AS Movimiento,
B.FundoID,
CASE WHEN B.FundoID = '03'
THEN A.Cantidad
ELSE 0 END AS SR_E_Cantidad,
0 AS SR_E_Precio,
0 AS SR_S_Cantidad,
0 AS SR_S_Precio,
CASE WHEN B.FundoID = '04'
THEN A.Cantidad
ELSE 0 END AS SJ_E_Cantidad,
0 AS SJ_E_Precio,
0 AS SJ_S_Cantidad,
0 AS SJ_S_Precio,
G.VigenteID,
'02' FuenteID
FROM TB_SalidaInventarioDetalle A
LEFT JOIN TB_SalidaInventario B ON A.FichaID = b.FichaID
LEFT JOIN TB_SalidaInventarioTipo C ON A.TipoID = C.TipoID
LEFT JOIN TB_Producto G ON A.ProductoID = G.VigenteID
WHERE A.TipoID IN ('06')
) A |
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';
-- -----------------------------------------------------
-- Part 2:
-- Schema Twitter
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `Twitter` DEFAULT CHARACTER SET utf8 ;
USE `Twitter` ;
-- -----------------------------------------------------
-- Table `Twitter`.`Users`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Twitter`.`Users` (
`user_id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`email` VARCHAR(45) NOT NULL,
`password` VARCHAR(45) NOT NULL,
`is_person` TINYINT NULL DEFAULT 0 COMMENT '\n',
`handle` VARCHAR(45) NOT NULL,
`discription` CHAR(255) NULL,
`is_hidden` TINYINT NULL DEFAULT 0,
PRIMARY KEY (`user_id`),
UNIQUE INDEX `email_UNIQUE` (`email` ASC),
UNIQUE INDEX `handle_UNIQUE` (`handle` ASC))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Twitter`.`Tweets`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Twitter`.`Tweets` (
`tweet_id` INT NOT NULL AUTO_INCREMENT,
`post` CHAR(160) NOT NULL,
`user_id` INT NOT NULL,
`timestamp` datetime NOT NULL DEFAULT now(),
INDEX `user_id_UNIQUE` (`user_id` ASC),
INDEX `user_id_idx` (`tweet_id` ASC),
CONSTRAINT `user_id`
FOREIGN KEY (`user_id`)
REFERENCES `Twitter`.`Users` (`user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Twitter`.`Follows`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Twitter`.`Follows` (
`Follower_id` INT NOT NULL,
`Followee_id` INT NOT NULL,
PRIMARY KEY (`Follower_id`, `Followee_id`),
CONSTRAINT `Follower_id`
FOREIGN KEY (`Follower_id`)
REFERENCES `Twitter`.`Users` (`user_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `Followee_id`
FOREIGN KEY (`Followee_id`)
REFERENCES `Twitter`.`Users` (`user_id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Twitter`.`Hashtag`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Twitter`.`Hashtag` (
`hash_id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`hash_id`),
UNIQUE INDEX `name_UNIQUE` (`name` ASC))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Twitter`.`Hashtags_in_tweets`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Twitter`.`Hashtags_in_tweets` (
`hash_id` INT NOT NULL,
`tweet_id` INT NOT NULL,
PRIMARY KEY (`hash_id`, `tweet_id`),
CONSTRAINT `hash_id`
FOREIGN KEY (`hash_id`)
REFERENCES `Twitter`.`Hashtag` (`hash_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `tweet_id`
FOREIGN KEY (`tweet_id`)
REFERENCES `Twitter`.`Tweets` (`tweet_id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Twitter`.`Likes`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Twitter`.`Likes` (
`user_id` INT NOT NULL,
`tweet_id` INT NOT NULL,
PRIMARY KEY (`tweet_id`, `user_id`),
INDEX `iser_id_idx` (`user_id` ASC),
INDEX `tweet_id_idx` (`tweet_id` ASC),
CONSTRAINT `Likes_user_id`
FOREIGN KEY (`user_id`)
REFERENCES `Twitter`.`Users` (`user_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `Likes_tweet_id`
FOREIGN KEY (`tweet_id`)
REFERENCES `Twitter`.`Tweets` (`tweet_id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Twitter`.`Interests`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Twitter`.`interests` (
`user_id` INT NOT NULL,
`hash_id` INT NOT NULL,
PRIMARY KEY (`user_id`, `hash_id`),
INDEX `user_id_idx` (`user_id` ASC),
INDEX `hash_id_idx` (`hash_id` ASC),
CONSTRAINT `interest_user_id`
FOREIGN KEY (`user_id`)
REFERENCES `Twitter`.`Users` (`user_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `interest_hash_id`
FOREIGN KEY (`hash_id`)
REFERENCES `Twitter`.`Hashtag` (`hash_id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; |
create table changeset_profile (
name varchar(255) not null unique,
last_run timestamp
);
|
CREATE PROC Maestro.Usp_Sel_CategoriaMovimiento_By_Abreviatura
@Abreviatura VARCHAR(50)
AS
BEGIN
SELECT [ID]
,[IdTipoMovimiento]
,[Nombre]
,[Abreviatura]
,[FlagCheque]
,[FlagTransferencia]
,[IdCategoriaTipoMovimientoRelacion]
FROM [Maestro].[CategoriaTipoMovimiento]
WHERE Abreviatura = @Abreviatura
END |
-- PROJECT_META_ATTRIBUTE
-- select pma.* from ifx_projects. project p, ifx_projects. project_meta_attribute pma where p.projet_is_public = 1 and p.projet_id = pma.projma_projet_id;
SELECT
'INSERT INTO project_meta_attribute ( projma_id, projma_projet_id, projma_lkuvlu_attribute_id, projma_is_required, projma_options, projma_attribute_desc, projma_actor_created_by, projma_create_date, projma_modified_date, projma_actor_modified_by, projma_is_active, projma_ontology ) VALUES ( ',
projma_id, ",",
projma_projet_id, ",",
projma_lkuvlu_attribute_id, ",",
projma_is_required, ",",
CONCAT('\"',projma_options,'\"') , ",",
CONCAT('\"',projma_attribute_desc,'\"') , ",",
projma_actor_created_by, ", ",
CONCAT('\"',projma_create_date,'\"') , ",",
CONCAT('\"',projma_modified_date,'\"') , ",",
projma_actor_modified_by, ", ",
projma_is_active, ", ",
CONCAT('\"',projma_ontology,'\"'),
' ) ON DUPLICATE KEY UPDATE ',
'projma_projet_id=',projma_projet_id,
',projma_lkuvlu_attribute_id=',projma_lkuvlu_attribute_id, ',projma_is_required=',projma_is_required,
',projma_options=',CONCAT('\"',projma_options,'\"'), ',projma_attribute_desc=',CONCAT('\"',projma_attribute_desc,'\"'),
',projma_actor_created_by=',projma_actor_created_by, ',projma_create_date=',CONCAT('\"',projma_create_date,'\"'),
',projma_modified_date=',CONCAT('\"',projma_modified_date,'\"'), ',projma_actor_modified_by=',projma_actor_modified_by,
',projma_is_active=',projma_is_active, ',projma_ontology=',CONCAT('\"',projma_ontology,'\"'),';'
FROM ifx_projects.project p, ifx_projects.project_meta_attribute pma
WHERE p.projet_id = pma.projma_projet_id
;
|
-- phpMyAdmin SQL Dump
-- version 4.9.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Feb 03, 2020 at 01:52 AM
-- Server version: 10.4.8-MariaDB
-- PHP Version: 7.1.32
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: `csms`
--
-- --------------------------------------------------------
--
-- Table structure for table `chairperson`
--
CREATE TABLE `chairperson` (
`Chair_ID` int(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `course`
--
CREATE TABLE `course` (
`Course_ID` int(255) NOT NULL,
`Course_Name` varchar(255) NOT NULL,
`Credit_Units` int(255) NOT NULL,
`Lec_Units` int(255) NOT NULL,
`Lab_Units` int(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `course_list`
--
CREATE TABLE `course_list` (
`Course_List_ID` int(255) NOT NULL,
`Course_ID` int(255) NOT NULL,
`Semester` int(255) NOT NULL,
`SY_ID` int(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `course_offering`
--
CREATE TABLE `course_offering` (
`CO_ID` int(255) NOT NULL,
`Teacher_ID` varchar(255) NOT NULL,
`Course_List_ID` varchar(255) NOT NULL,
`Time_ID` varchar(255) NOT NULL,
`No._of_Section` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `course_request`
--
CREATE TABLE `course_request` (
`SR_ID` int(255) NOT NULL,
`Course_ID` int(255) NOT NULL,
`Chair_ID` int(255) NOT NULL,
`Description` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `department`
--
CREATE TABLE `department` (
`Department_ID` int(255) NOT NULL,
`Department_Name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `faculty`
--
CREATE TABLE `faculty` (
`Faculty_ID` int(255) NOT NULL,
`Password` varchar(255) NOT NULL,
`First_name` varchar(255) NOT NULL,
`Middle_name` varchar(255) NOT NULL,
`Last_name` varchar(255) NOT NULL,
`Faculty_type` int(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `school_year`
--
CREATE TABLE `school_year` (
`SY_ID` int(255) NOT NULL,
`Curriculum_Year` int(255) NOT NULL,
`Description` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `teacher`
--
CREATE TABLE `teacher` (
`Teacher_ID` int(255) NOT NULL,
`Loading_scheme` int(255) NOT NULL,
`Preferred_time` varchar(255) NOT NULL,
`Past_Courses_teached` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `time`
--
CREATE TABLE `time` (
`Time_ID` int(255) NOT NULL,
`Room` varchar(255) NOT NULL,
`Day` varchar(255) NOT NULL,
`Start_time` varchar(255) NOT NULL,
`End_time` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `chairperson`
--
ALTER TABLE `chairperson`
ADD PRIMARY KEY (`Chair_ID`);
--
-- Indexes for table `course`
--
ALTER TABLE `course`
ADD PRIMARY KEY (`Course_ID`);
--
-- Indexes for table `course_list`
--
ALTER TABLE `course_list`
ADD PRIMARY KEY (`Course_List_ID`);
--
-- Indexes for table `course_offering`
--
ALTER TABLE `course_offering`
ADD PRIMARY KEY (`CO_ID`);
--
-- Indexes for table `course_request`
--
ALTER TABLE `course_request`
ADD PRIMARY KEY (`SR_ID`);
--
-- Indexes for table `department`
--
ALTER TABLE `department`
ADD PRIMARY KEY (`Department_ID`);
--
-- Indexes for table `faculty`
--
ALTER TABLE `faculty`
ADD PRIMARY KEY (`Faculty_ID`);
--
-- Indexes for table `school_year`
--
ALTER TABLE `school_year`
ADD PRIMARY KEY (`SY_ID`);
--
-- Indexes for table `teacher`
--
ALTER TABLE `teacher`
ADD PRIMARY KEY (`Teacher_ID`);
--
-- Indexes for table `time`
--
ALTER TABLE `time`
ADD PRIMARY KEY (`Time_ID`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `chairperson`
--
ALTER TABLE `chairperson`
MODIFY `Chair_ID` int(255) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `department`
--
ALTER TABLE `department`
MODIFY `Department_ID` int(255) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `faculty`
--
ALTER TABLE `faculty`
MODIFY `Faculty_ID` int(255) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `teacher`
--
ALTER TABLE `teacher`
MODIFY `Teacher_ID` int(255) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
/*
Navicat MySQL Data Transfer
Source Server : localhost_3306
Source Server Version : 50617
Source Host : localhost:3306
Source Database : store
Target Server Type : MYSQL
Target Server Version : 50617
File Encoding : 65001
Date: 2016-06-08 15:44:21
*/
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `pre_member`;
CREATE TABLE `pre_member` (
`uid` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户UID',
`email` char(255) DEFAULT NULL COMMENT '邮箱',
`mobile` char(255) DEFAULT NULL COMMENT '电话号码',
`nickname` char(255) DEFAULT NULL COMMENT '用户昵称',
`name` char(255) DEFAULT NULL COMMENT '用户名称',
`pwcode` char(255) NOT NULL DEFAULT '' COMMENT '用户密码随机字符串',
`avatar` char(255) NOT NULL DEFAULT '' COMMENT '头像',
`level` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '用户级别',
`token` char(255) NOT NULL DEFAULT '' COMMENT '用户TOKEN',
`datetime` DATETIME NOT NULL DEFAULT '1970-01-01 00:00:00' COMMENT '注册时间',
UNIQUE KEY `nickname` (`nickname`),
UNIQUE KEY `email` (`email`),
UNIQUE KEY `mobile` (`mobile`),
PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='会员表';
DROP TABLE IF EXISTS `pre_member_weixin`;
CREATE TABLE `pre_member_weixin` (
`uid` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户凭证',
`wx_openid` varchar(255) NOT NULL DEFAULT '' COMMENT '用户姓名',
`wx_nickname` varchar(255) NOT NULL DEFAULT '' COMMENT '用户姓名',
`wx_sex` varchar(255) NOT NULL DEFAULT '' COMMENT '用户姓名',
`wx_language` varchar(255) NOT NULL DEFAULT '' COMMENT '用户姓名',
`wx_city` varchar(255) NOT NULL DEFAULT '' COMMENT '用户姓名',
`wx_province` varchar(255) NOT NULL DEFAULT '' COMMENT '用户姓名',
`wx_country` varchar(255) NOT NULL DEFAULT '' COMMENT '用户姓名',
`wx_headimgurl` varchar(255) NOT NULL DEFAULT '' COMMENT '用户姓名',
PRIMARY KEY (`uid`),
UNIQUE KEY `wx_openid` (`wx_openid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='会员微信授权表';
DROP TABLE IF EXISTS `pre_member_count`;
CREATE TABLE `pre_member_count` (
`uid` mediumint(8) unsigned NOT NULL DEFAULT '0' ,
`credits1` decimal(14,2) DEFAULT 0.00 COMMENT '积分字段1',
PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='会员计数表';
DROP TABLE IF EXISTS `pre_member_verify`;
CREATE TABLE `pre_member_verify` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`type` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT ' 0 注册邮箱 1 注册手机号',
`account` char(255) NOT NULL DEFAULT '' COMMENT '验证账号:手机号或邮箱',
`code` char(255) NOT NULL DEFAULT '',
`expiration` DATETIME NOT NULL DEFAULT '1970-01-01 00:00:00' COMMENT '有效期',
`datetime` DATETIME NOT NULL DEFAULT '1970-01-01 00:00:00' COMMENT '注册时间',
PRIMARY KEY (`id`),
KEY `typeaccount` (`type`,`account`),
KEY `expiration` (`expiration`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='会员验证表';
|
CREATE TABLE SALARIES (
id NUMBER(*,0) PRIMARY KEY,
employee_id NUMBER(*,0) NOT NULL,
project_id NUMBER(*,0),
salary NUMBER(10,2),
FOREIGN KEY (employee_id) REFERENCES EMPLOYEES(id),
FOREIGN KEY (project_id) REFERENCES PROJECTS(id)
);
CREATE TABLE EMPLOYEES (
id NUMBER(*,0) PRIMARY KEY,
manager_id NUMBER(*,0),
date_of_joining DATE NOT NULL,
full_name VARCHAR2(255 BYTE) NOT NULL,
FOREIGN KEY (manager_id) REFERENCES EMPLOYEES(id)
);
CREATE TABLE PROJECTS (
id NUMBER(*,0) PRIMARY KEY,
code VARCHAR2(255 BYTE) NOT NULL,
manager_id NUMBER(*,0),
budget NUMBER(10,2) NOT NULL,
date_of_beginning DATE,
date_of_ending DATE,
FOREIGN KEY (manager_id) REFERENCES EMPLOYEES(id)
);
SELECT COUNT(*) FROM EMPLOYEES
INNER JOIN PROJECTS ON PROJECTS.MANAGER_ID = EMPLOYEES.ID
WHERE PROJECTS.CODE = '44905736599';
SELECT FULL_NAME FROM EMPLOYEES
INNER JOIN SALARIES ON SALARIES.EMPLOYEE_ID = EMPLOYEES.ID
WHERE SALARY >= 1000 AND SALARY <= 2500;
|
CREATE DATABASE IF NOT EXISTS db;
USE db;
CREATE TABLE rebelde (
oid_rebelde INT NOT NULL AUTO_INCREMENT primary key,
nome VARCHAR(50) not null,
idade int not null,
genero VARCHAR(1) not null,
qtd_traicoes int not null default 0
);
CREATE TABLE localizacao (
oid_localizacao INT NOT NULL AUTO_INCREMENT primary key,
latitude int not null,
longitude int not null,
nome VARCHAR(100) not null,
oid_rebelde INT NOT NULL,
CONSTRAINT fk_localizacao_rebelde FOREIGN KEY (oid_rebelde) REFERENCES rebelde(oid_rebelde)
);
CREATE TABLE item (
oid_item INT NOT NULL AUTO_INCREMENT primary key,
nome VARCHAR(50) not null,
pontuacao int not null
);
CREATE TABLE rebelde_item (
oid_rebelde_item INT NOT NULL AUTO_INCREMENT primary key,
oid_rebelde INT NOT NULL,
oid_item INT NOT NULL,
quantidade int not null,
CONSTRAINT fk_rebelde_item FOREIGN KEY (oid_rebelde) REFERENCES rebelde(oid_rebelde),
CONSTRAINT fk_item FOREIGN KEY (oid_item) REFERENCES item(oid_item)
);
INSERT INTO item( nome, pontuacao )
VALUES( 'Arma', 4 );
INSERT INTO item( nome, pontuacao )
VALUES( 'Municao', 3 );
INSERT INTO item( nome, pontuacao )
VALUES( 'Agua', 2 );
INSERT INTO item( nome, pontuacao )
VALUES( 'Comida', 1 );
COMMIT; |
CREATE TABLE registros (
codHito INTEGER NOT NULL,
codregistros INTEGER NOT NULL,
entregatable VARCHAR(120) NULL,
PRIMARY KEY(codHito, codregistros)
);
CREATE TABLE foro (
codforo SERIAL NOT NULL,
autor VARCHAR(45) NULL,
titulo VARCHAR(45) NULL,
mensaje TEXT NULL,
PRIMARY KEY(codforo)
);
CREATE TABLE Usuario (
idUsuario SERIAL NOT NULL,
login VARCHAR(45) UNIQUE,
passwd VARCHAR(45) NULL,
habilitada BOOL NOT NULL,
PRIMARY KEY(idUsuario)
);
CREATE TABLE Funcion (
codFuncion SERIAL NOT NULL,
tipoFuncion VARCHAR(45) NULL,
PRIMARY KEY(codFuncion)
);
CREATE TABLE Rol (
codRol SERIAL NOT NULL,
tipoRol VARCHAR(45) NULL,
PRIMARY KEY(codRol)
);
CREATE TABLE Tipo_Socio (
codTipo_Socio SERIAL NOT NULL,
nombreTipo VARCHAR(45) NULL,
PRIMARY KEY(codTipo_Socio)
);
CREATE TABLE App (
codApp SERIAL NOT NULL,
nombreApp VARCHAR(45) NULL,
PRIMARY KEY(codApp)
);
CREATE TABLE Grupo_Empresa (
CodGrupo_Empresa SERIAL NOT NULL,
Usuario_idUsuario INTEGER NOT NULL,
nombrelargoGE VARCHAR(45) UNIQUE,
nombreCortoGE VARCHAR(45) NOT NULL,
correoGE VARCHAR(45) NOT NULL,
direccionGE VARCHAR(45) NOT NULL,
telefonoGE INTEGER NOT NULL,
PRIMARY KEY(CodGrupo_Empresa, Usuario_idUsuario),
FOREIGN KEY(Usuario_idUsuario)
REFERENCES Usuario(idUsuario)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE Telf_GE (
idTelf_GE SERIAL NOT NULL,
Grupo_Empresa_CodGrupo_Empresa INTEGER NOT NULL,
Grupo_Empresa_Usuario_idUsuario INTEGER NOT NULL,
numeroTelf INTEGER NULL,
PRIMARY KEY(idTelf_GE, Grupo_Empresa_CodGrupo_Empresa, Grupo_Empresa_Usuario_idUsuario),
FOREIGN KEY(Grupo_Empresa_CodGrupo_Empresa, Grupo_Empresa_Usuario_idUsuario)
REFERENCES Grupo_Empresa(CodGrupo_Empresa, Usuario_idUsuario)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE consultor
(
idconsultor SERIAL NOT NULL,
usuario_idusuario integer NOT NULL,
nombreconsultor character varying(45),
correoconsultor character varying(45),
telefonoconsultor INTEGER NOT NULL,
CONSTRAINT consultor_pkey PRIMARY KEY (idconsultor, usuario_idusuario),
CONSTRAINT consultor_usuario_idusuario_fkey FOREIGN KEY (usuario_idusuario)
REFERENCES usuario (idusuario) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT consultor_idconsultor_key UNIQUE (idconsultor)
);
CREATE TABLE calendario
(
codcalendario SERIAL NOT NULL,
grupo_empresa_codgrupo_empresa integer NOT NULL,
grupo_empresa_usuario_idusuario integer NOT NULL,
dia_reunion_fijado boolean DEFAULT false,
CONSTRAINT calendario_pkey PRIMARY KEY (codcalendario, grupo_empresa_codgrupo_empresa, grupo_empresa_usuario_idusuario),
CONSTRAINT calendario_grupo_empresa_codgrupo_empresa_fkey FOREIGN KEY (grupo_empresa_codgrupo_empresa, grupo_empresa_usuario_idusuario)
REFERENCES grupo_empresa (codgrupo_empresa, usuario_idusuario) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
CREATE TABLE plan_pago
(
codplan_pago SERIAL NOT NULL,
calendario_codcalendario integer NOT NULL,
calendario_grupo_empresa_codgrupo_empresa integer NOT NULL,
calendario_grupo_empresa_usuario_idusuario integer NOT NULL,
montototal real,
porcentajesatisfaccion integer,
CONSTRAINT plan_pago_pkey PRIMARY KEY (codplan_pago, calendario_codcalendario, calendario_grupo_empresa_codgrupo_empresa, calendario_grupo_empresa_usuario_idusuario),
CONSTRAINT plan_pago_calendario_codcalendario_fkey FOREIGN KEY (calendario_codcalendario, calendario_grupo_empresa_codgrupo_empresa, calendario_grupo_empresa_usuario_idusuario)
REFERENCES calendario (codcalendario, grupo_empresa_codgrupo_empresa, grupo_empresa_usuario_idusuario) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
CREATE TABLE Socio (
idSocio SERIAL NOT NULL,
Grupo_Empresa_CodGrupo_Empresa INTEGER NOT NULL,
Tipo_Socio_codTipo_Socio INTEGER NOT NULL,
Grupo_Empresa_Usuario_idUsuario INTEGER NOT NULL,
Usuario_idUsuario INTEGER NOT NULL,
nombreSocio VARCHAR(15) NULL,
apellidosSocio VARCHAR(25) NULL,
estadoCivil VARCHAR(15) NULL,
direccion VARCHAR(45) NULL,
edad INTEGER NULL,
profecion VARCHAR(45) NULL,
PRIMARY KEY(idSocio, Grupo_Empresa_CodGrupo_Empresa, Tipo_Socio_codTipo_Socio, Grupo_Empresa_Usuario_idUsuario),
FOREIGN KEY(Grupo_Empresa_CodGrupo_Empresa, Grupo_Empresa_Usuario_idUsuario)
REFERENCES Grupo_Empresa(CodGrupo_Empresa, Usuario_idUsuario)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
FOREIGN KEY(Tipo_Socio_codTipo_Socio)
REFERENCES Tipo_Socio(codTipo_Socio)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
FOREIGN KEY(Usuario_idUsuario)
REFERENCES Usuario(idUsuario)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE User_Rol (
codUser_Rol SERIAL NOT NULL,
Usuario_idUsuario INTEGER NOT NULL,
Rol_codRol INTEGER NOT NULL,
PRIMARY KEY(codUser_Rol, Usuario_idUsuario, Rol_codRol),
FOREIGN KEY(Usuario_idUsuario)
REFERENCES Usuario(idUsuario)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
FOREIGN KEY(Rol_codRol)
REFERENCES Rol(codRol)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE evaluacion_semanal
(
codevaluacion_semanal serial NOT NULL,
calendario_codcalendario integer NOT NULL,
calendario_grupo_empresa_codgrupo_empresa integer NOT NULL,
calendario_grupo_empresa_usuario_idusuario integer NOT NULL,
fecha date,
CONSTRAINT evaluacion_semanal_pkey PRIMARY KEY (codevaluacion_semanal, calendario_codcalendario, calendario_grupo_empresa_codgrupo_empresa, calendario_grupo_empresa_usuario_idusuario),
CONSTRAINT evaluacion_semanal_calendario_codcalendario_fkey FOREIGN KEY (calendario_codcalendario, calendario_grupo_empresa_codgrupo_empresa, calendario_grupo_empresa_usuario_idusuario)
REFERENCES calendario (codcalendario, grupo_empresa_codgrupo_empresa, grupo_empresa_usuario_idusuario) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
CREATE TABLE Tipo_Criterio (
id_tipo serial NOT NULL,
tipo VARCHAR(15) NULL,
PRIMARY KEY(id_tipo)
);
CREATE TABLE Registro_Evaluacion_Final (
idRegistro_Evaluacion_Final serial NOT NULL,
Consultor_Usuario_idUsuario INTEGER NOT NULL,
Consultor_idConsultor INTEGER NOT NULL,
PRIMARY KEY(idRegistro_Evaluacion_Final, Consultor_Usuario_idUsuario, Consultor_idConsultor),
FOREIGN KEY(Consultor_idConsultor, Consultor_Usuario_idUsuario)
REFERENCES Consultor(idConsultor, Usuario_idUsuario)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE Criterio (
id_criterio serial NOT NULL,
Tipo_Criterio_id_tipo INTEGER NOT NULL,
Registro_Evaluacion_Final_idRegistro_Evaluacion_Final INTEGER NOT NULL,
Registro_Evaluacion_Final_Consultor_idConsultor INTEGER NOT NULL,
Registro_Evaluacion_Final_Consultor_Usuario_idUsuario INTEGER NOT NULL,
porcentaje INTEGER NULL,
PRIMARY KEY(id_criterio, Tipo_Criterio_id_tipo, Registro_Evaluacion_Final_idRegistro_Evaluacion_Final, Registro_Evaluacion_Final_Consultor_idConsultor, Registro_Evaluacion_Final_Consultor_Usuario_idUsuario),
FOREIGN KEY(Tipo_Criterio_id_tipo)
REFERENCES Tipo_Criterio(id_tipo)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
FOREIGN KEY(Registro_Evaluacion_Final_idRegistro_Evaluacion_Final, Registro_Evaluacion_Final_Consultor_Usuario_idUsuario, Registro_Evaluacion_Final_Consultor_idConsultor)
REFERENCES Registro_Evaluacion_Final(idRegistro_Evaluacion_Final, Consultor_Usuario_idUsuario, Consultor_idConsultor)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE Evaluacion_final (
codEvaluacion_final INTEGER NOT NULL,
Criterio_Registro_Evaluacion_Final_idRegistro_Evaluacion_Final INTEGER NOT NULL,
Criterio_Tipo_Criterio_id_tipo INTEGER NOT NULL,
Criterio_id_criterio INTEGER NOT NULL,
Criterio_Registro_Evaluacion_Final_Consultor_Usuario_idUsuario INTEGER NOT NULL,
Criterio_Registro_Evaluacion_Final_Consultor_idConsultor INTEGER NOT NULL,
Grupo_Empresa_Usuario_idUsuario INTEGER NOT NULL,
Grupo_Empresa_CodGrupo_Empresa INTEGER NOT NULL,
fecha DATE NOT NULL,
nota INTEGER NOT NULL,
PRIMARY KEY(codEvaluacion_final, Criterio_Registro_Evaluacion_Final_idRegistro_Evaluacion_Final, Criterio_Tipo_Criterio_id_tipo, Criterio_id_criterio, Criterio_Registro_Evaluacion_Final_Consultor_Usuario_idUsuario, Criterio_Registro_Evaluacion_Final_Consultor_idConsultor, Grupo_Empresa_Usuario_idUsuario, Grupo_Empresa_CodGrupo_Empresa),
FOREIGN KEY(Criterio_id_criterio, Criterio_Tipo_Criterio_id_tipo, Criterio_Registro_Evaluacion_Final_idRegistro_Evaluacion_Final, Criterio_Registro_Evaluacion_Final_Consultor_idConsultor, Criterio_Registro_Evaluacion_Final_Consultor_Usuario_idUsuario)
REFERENCES Criterio(id_criterio, Tipo_Criterio_id_tipo, Registro_Evaluacion_Final_idRegistro_Evaluacion_Final, Registro_Evaluacion_Final_Consultor_idConsultor, Registro_Evaluacion_Final_Consultor_Usuario_idUsuario)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
FOREIGN KEY(Grupo_Empresa_CodGrupo_Empresa, Grupo_Empresa_Usuario_idUsuario)
REFERENCES Grupo_Empresa(CodGrupo_Empresa, Usuario_idUsuario)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE Funcion_App (
codFuncion_App SERIAL NOT NULL,
App_codApp INTEGER NOT NULL,
Funcion_codFuncion INTEGER NOT NULL,
PRIMARY KEY(codFuncion_App, App_codApp, Funcion_codFuncion),
FOREIGN KEY(App_codApp)
REFERENCES App(codApp)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
FOREIGN KEY(Funcion_codFuncion)
REFERENCES Funcion(codFuncion)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE Rol_Funcion (
codRol_Funcion SERIAL NOT NULL,
Rol_codRol INTEGER NOT NULL,
Funcion_codFuncion INTEGER NOT NULL,
PRIMARY KEY(codRol_Funcion, Rol_codRol, Funcion_codFuncion),
FOREIGN KEY(Rol_codRol)
REFERENCES Rol(codRol)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
FOREIGN KEY(Funcion_codFuncion)
REFERENCES Funcion(codFuncion)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE Cons_Actividad (
codCons_Actividad SERIAL NOT NULL,
Consultor_Usuario_idUsuario INTEGER NOT NULL,
Consultor_idConsultor INTEGER NOT NULL,
visiblePara VARCHAR(30) NULL,
requiereRespuesta VARCHAR(15) NULL,
fechaInicio TIMESTAMP NULL,
fechaFin TIMESTAMP NULL,
horaInicio TIME NULL,
horaFin TIME NULL,
titulo VARCHAR(30) NULL,
descripcion TEXT NULL,
activo BOOL NULL,
contestada BOOL NULL,
PRIMARY KEY(codCons_Actividad, Consultor_Usuario_idUsuario, Consultor_idConsultor),
FOREIGN KEY(Consultor_idConsultor, Consultor_Usuario_idUsuario)
REFERENCES Consultor(idConsultor, Usuario_idUsuario)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE GE_Documento (
idGE_Documento SERIAL NOT NULL,
Grupo_Empresa_CodGrupo_Empresa INTEGER NOT NULL,
Grupo_Empresa_Usuario_idUsuario INTEGER NOT NULL,
nombreDocumento VARCHAR(45) NULL,
pathDocumentoGE VARCHAR(120) NULL,
PRIMARY KEY(idGE_Documento, Grupo_Empresa_CodGrupo_Empresa, Grupo_Empresa_Usuario_idUsuario),
FOREIGN KEY(Grupo_Empresa_CodGrupo_Empresa, Grupo_Empresa_Usuario_idUsuario)
REFERENCES Grupo_Empresa(CodGrupo_Empresa, Usuario_idUsuario)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE Cons_Documento (
idCons_Documento SERIAL NOT NULL,
Consultor_idConsultor INTEGER NOT NULL,
nombreDocumento VARCHAR(45) NULL,
descripcionConsultorDocumento TEXT NULL,
pathDocumentoConsultor VARCHAR(120) NULL,
PRIMARY KEY(idCons_Documento),
FOREIGN KEY(Consultor_idConsultor)
REFERENCES Consultor(idConsultor)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE Proyecto (
codProyecto VARCHAR(10) NOT NULL,
nombreProyecto VARCHAR(45) NULL,
fechaFinProyecto DATE NULL,
vigente BOOL NULL,
PRIMARY KEY(codProyecto)
);
CREATE TABLE detalle_ge
(
iddetalle_ge serial NOT NULL,
evaluacion_semanal_calendario_grupo_empresa_usuario_idusuario integer NOT NULL,
evaluacion_semanal_calendario_grupo_empresa_codgrupo_empresa integer NOT NULL,
evaluacion_semanal_calendario_codcalendario integer NOT NULL,
evaluacion_semanal_codevaluacion_semanal integer NOT NULL,
rol character varying(120),
esperado character varying(120),
CONSTRAINT detalle_ge_pkey PRIMARY KEY (iddetalle_ge, evaluacion_semanal_calendario_grupo_empresa_usuario_idusuario, evaluacion_semanal_calendario_grupo_empresa_codgrupo_empresa, evaluacion_semanal_calendario_codcalendario, evaluacion_semanal_codevaluacion_semanal),
CONSTRAINT detalle_ge_evaluacion_semanal_codevaluacion_semanal_fkey FOREIGN KEY (evaluacion_semanal_codevaluacion_semanal, evaluacion_semanal_calendario_codcalendario, evaluacion_semanal_calendario_grupo_empresa_codgrupo_empresa, evaluacion_semanal_calendario_grupo_empresa_usuario_idusuario)
REFERENCES evaluacion_semanal (codevaluacion_semanal, calendario_codcalendario, calendario_grupo_empresa_codgrupo_empresa, calendario_grupo_empresa_usuario_idusuario) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
CREATE TABLE detalle_cons
(
iddetalle_cons serial NOT NULL,
consultor_idconsultor integer NOT NULL,
detalle_ge_evaluacion_semanal_codevaluacion_semanal integer NOT NULL,
detalle_ge_evaluacion_semanal_calendario_codcalendario integer NOT NULL,
detalle_ge_evaluacion_semanal_calendario_grupo_empresa_codgrupo integer NOT NULL,
detalle_ge_evaluacion_semanal_calendario_grupo_empresa_usuario_ integer NOT NULL,
detalle_ge_iddetalle_ge integer NOT NULL,
realizado text,
observaciones text,
detalle_esperado text,
CONSTRAINT detalle_cons_pkey PRIMARY KEY (iddetalle_cons, consultor_idconsultor, detalle_ge_evaluacion_semanal_codevaluacion_semanal, detalle_ge_evaluacion_semanal_calendario_codcalendario, detalle_ge_evaluacion_semanal_calendario_grupo_empresa_codgrupo, detalle_ge_evaluacion_semanal_calendario_grupo_empresa_usuario_, detalle_ge_iddetalle_ge),
CONSTRAINT detalle_cons_consultor_idconsultor_fkey FOREIGN KEY (consultor_idconsultor)
REFERENCES consultor (idconsultor) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT detalle_cons_detalle_ge_iddetalle_ge_fkey FOREIGN KEY (detalle_ge_iddetalle_ge, detalle_ge_evaluacion_semanal_calendario_grupo_empresa_usuario_, detalle_ge_evaluacion_semanal_calendario_grupo_empresa_codgrupo, detalle_ge_evaluacion_semanal_calendario_codcalendario, detalle_ge_evaluacion_semanal_codevaluacion_semanal)
REFERENCES detalle_ge (iddetalle_ge, evaluacion_semanal_calendario_grupo_empresa_usuario_idusuario, evaluacion_semanal_calendario_grupo_empresa_codgrupo_empresa, evaluacion_semanal_calendario_codcalendario, evaluacion_semanal_codevaluacion_semanal) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
CREATE TABLE consultor_proyecto_grupo_empresa (
Consultor_Usuario_idUsuario INTEGER NOT NULL,
Consultor_idConsultor INTEGER NOT NULL,
Grupo_Empresa_Usuario_idUsuario INTEGER NOT NULL,
Grupo_Empresa_CodGrupo_Empresa INTEGER NOT NULL,
Proyecto_codProyecto VARCHAR(10) NOT NULL,
PRIMARY KEY(Consultor_Usuario_idUsuario, Consultor_idConsultor, Grupo_Empresa_Usuario_idUsuario, Grupo_Empresa_CodGrupo_Empresa, Proyecto_codProyecto),
FOREIGN KEY(Consultor_idConsultor, Consultor_Usuario_idUsuario)
REFERENCES Consultor(idConsultor, Usuario_idUsuario)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
FOREIGN KEY(Grupo_Empresa_CodGrupo_Empresa, Grupo_Empresa_Usuario_idUsuario)
REFERENCES Grupo_Empresa(CodGrupo_Empresa, Usuario_idUsuario)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
FOREIGN KEY(Proyecto_codProyecto)
REFERENCES Proyecto(codProyecto)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE Hito_Pagable (
codHito_Pagable SERIAL NOT NULL,
Plan_Pago_codPlan_Pago INTEGER NOT NULL,
Plan_Pago_Calendario_codCalendario INTEGER NOT NULL,
Plan_Pago_Calendario_Grupo_Empresa_CodGrupo_Empresa INTEGER NOT NULL,
Plan_Pago_Calendario_Grupo_Empresa_Usuario_idUsuario INTEGER NOT NULL,
hitoevento VARCHAR(120) NULL,
porcentajepago INTEGER NULL,
monto REAL NULL,
fechapago DATE NULL,
PRIMARY KEY(codHito_Pagable, Plan_Pago_codPlan_Pago, Plan_Pago_Calendario_codCalendario, Plan_Pago_Calendario_Grupo_Empresa_CodGrupo_Empresa, Plan_Pago_Calendario_Grupo_Empresa_Usuario_idUsuario),
FOREIGN KEY(Plan_Pago_codPlan_Pago, Plan_Pago_Calendario_Grupo_Empresa_Usuario_idUsuario, Plan_Pago_Calendario_Grupo_Empresa_CodGrupo_Empresa, Plan_Pago_Calendario_codCalendario)
REFERENCES Plan_Pago(codPlan_Pago, Calendario_Grupo_Empresa_Usuario_idUsuario, Calendario_Grupo_Empresa_CodGrupo_Empresa, Calendario_codCalendario)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE entregables (
codentregables SERIAL NOT NULL,
Hito_Pagable_Plan_Pago_Calendario_Grupo_Empresa_Usuario_idUsuario INTEGER NOT NULL,
Hito_Pagable_Plan_Pago_Calendario_Grupo_Empresa_CodGrupo_Empresa INTEGER NOT NULL,
Hito_Pagable_Plan_Pago_Calendario_codCalendario INTEGER NOT NULL,
Hito_Pagable_Plan_Pago_codPlan_Pago INTEGER NOT NULL,
Hito_Pagable_codHito_Pagable INTEGER NOT NULL,
entregable VARCHAR(120) NULL,
PRIMARY KEY(codentregables, Hito_Pagable_Plan_Pago_Calendario_Grupo_Empresa_Usuario_idUsuario, Hito_Pagable_Plan_Pago_Calendario_Grupo_Empresa_CodGrupo_Empresa, Hito_Pagable_Plan_Pago_Calendario_codCalendario, Hito_Pagable_Plan_Pago_codPlan_Pago, Hito_Pagable_codHito_Pagable),
FOREIGN KEY(Hito_Pagable_codHito_Pagable, Hito_Pagable_Plan_Pago_codPlan_Pago, Hito_Pagable_Plan_Pago_Calendario_codCalendario, Hito_Pagable_Plan_Pago_Calendario_Grupo_Empresa_CodGrupo_Empresa, Hito_Pagable_Plan_Pago_Calendario_Grupo_Empresa_Usuario_idUsuario)
REFERENCES Hito_Pagable(codHito_Pagable, Plan_Pago_codPlan_Pago, Plan_Pago_Calendario_codCalendario, Plan_Pago_Calendario_Grupo_Empresa_CodGrupo_Empresa, Plan_Pago_Calendario_Grupo_Empresa_Usuario_idUsuario)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE Pago_Consultor (
codPago_Consultor INTEGER NOT NULL,
Consultor_idConsultor INTEGER NOT NULL,
Consultor_Usuario_idUsuario INTEGER NOT NULL,
Hito_Pagable_Plan_Pago_codPlan_Pago INTEGER NOT NULL,
Hito_Pagable_codHito_Pagable INTEGER NOT NULL,
Hito_Pagable_Plan_Pago_Calendario_Grupo_Empresa_Usuario_idUsuario INTEGER NOT NULL,
Hito_Pagable_Plan_Pago_Calendario_Grupo_Empresa_CodGrupo_Empresa INTEGER NOT NULL,
Hito_Pagable_Plan_Pago_Calendario_codCalendario INTEGER NOT NULL,
hitooevento VARCHAR(120) NULL,
porcentajesatisfaccion INTEGER NULL,
porcentajeAlcazado INTEGER NULL,
estadoPago VARCHAR(45) NULL,
PRIMARY KEY(codPago_Consultor, Consultor_idConsultor, Consultor_Usuario_idUsuario, Hito_Pagable_Plan_Pago_codPlan_Pago, Hito_Pagable_codHito_Pagable, Hito_Pagable_Plan_Pago_Calendario_Grupo_Empresa_Usuario_idUsuario, Hito_Pagable_Plan_Pago_Calendario_Grupo_Empresa_CodGrupo_Empresa, Hito_Pagable_Plan_Pago_Calendario_codCalendario),
FOREIGN KEY(Hito_Pagable_codHito_Pagable, Hito_Pagable_Plan_Pago_codPlan_Pago, Hito_Pagable_Plan_Pago_Calendario_codCalendario, Hito_Pagable_Plan_Pago_Calendario_Grupo_Empresa_CodGrupo_Empresa, Hito_Pagable_Plan_Pago_Calendario_Grupo_Empresa_Usuario_idUsuario)
REFERENCES Hito_Pagable(codHito_Pagable, Plan_Pago_codPlan_Pago, Plan_Pago_Calendario_codCalendario, Plan_Pago_Calendario_Grupo_Empresa_CodGrupo_Empresa, Plan_Pago_Calendario_Grupo_Empresa_Usuario_idUsuario)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
FOREIGN KEY(Consultor_idConsultor, Consultor_Usuario_idUsuario)
REFERENCES Consultor(idConsultor, Usuario_idUsuario)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
INSERT INTO rol(tiporol)
VALUES ('administrador');
INSERT INTO rol(tiporol)
VALUES ('consultor');
INSERT INTO rol(tiporol)
VALUES ('empresa');
INSERT INTO rol(tiporol)
VALUES ('socio');
INSERT INTO usuario(
login, passwd,habilitada)
VALUES ( 'admin', 'admin',TRUE);
INSERT INTO user_rol(
usuario_idusuario, rol_codrol)
VALUES ('1', '1');
INSERT INTO tipo_socio(nombretipo)
VALUES ('representante legal');
INSERT INTO tipo_socio(codtipo_socio, nombretipo)
VALUES ('socio regular');
|
ALTER TABLE users DROP CONSTRAINT user_unique;
--;;
ALTER TABLE classes DROP CONSTRAINT class_unique;
--;;
ALTER TABLE ONLY users
DROP COLUMN guid;
--;;
ALTER TABLE ONLY classes
DROP COLUMN guid;
--;; |
@customer;
@custexit;
@plan;
@planrate;
@calls;
@callpls;
@schedule;
@credit;
@lnfixchr;
@speser;
@serfee;
@taxrate;
|
-- 최소 0번 수행 ~ 최대 조건까지 반복수행 while
set serveroutput on
declare
i number;
begin
-- 1에서부터 10까지 1씩 증가하는 값을 출력하는 while
i := 1 ;
-- 조건식
while i <= 10 loop
dbms_output.put_line(i);
i := i +1;
end loop;
-- 0에서 100사이의 홀수만 출력하는 while
i := 1;
while i < 101 loop
-- 1) if 함수를 쓰는 경우 if mod(i,2)=1 then
dbms_output.put_line(i);
-- end if;
-- i := i + 1
i := i+2;
end loop;
end;
/ |
/*
Navicat MySQL Data Transfer
Source Server : my
Source Server Version : 50528
Source Host : localhost:3306
Source Database : mall
Target Server Type : MYSQL
Target Server Version : 50528
File Encoding : 65001
Date: 2019-06-28 15:28:28
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for category
-- ----------------------------
DROP TABLE IF EXISTS `category`;
CREATE TABLE `category` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '商品类型的id',
`parent_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '父类型的id。一级类型没有父类型,填0。外键,参照category(id)',
`name` varchar(255) NOT NULL COMMENT '类型名称',
`is_first` tinyint(3) unsigned DEFAULT '0' COMMENT '是否是一级类型:1是一级类型,0不是一级类型',
`sort` tinyint(3) DEFAULT NULL COMMENT '同一个级的类型出现的顺序。如1,2。1在2的前面',
`created` datetime DEFAULT NULL COMMENT '创建时间',
`modify` datetime DEFAULT NULL COMMENT '修改时间',
`is_delete` tinyint(3) unsigned DEFAULT '0' COMMENT '1删除,0未删除',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of category
-- ----------------------------
INSERT INTO `category` VALUES ('1', '0', '电子产品', '1', '1', '2018-03-13 17:26:00', '2018-03-30 14:46:49', '0');
INSERT INTO `category` VALUES ('7', '14', '动画', '0', '1', '2018-03-22 16:49:12', '2018-03-30 14:24:25', '0');
INSERT INTO `category` VALUES ('8', '0', '金银珠宝', '1', '1', '2018-03-22 16:49:41', '2018-03-30 10:01:28', '0');
INSERT INTO `category` VALUES ('9', '1', '轻音乐', '0', '1', '2018-03-22 16:50:13', '2018-03-30 13:55:16', '0');
INSERT INTO `category` VALUES ('13', '1', '家电', '0', '1', '2018-03-22 17:45:19', '2018-03-22 17:45:19', '0');
INSERT INTO `category` VALUES ('14', '0', '手机产品', '1', '1', '2018-03-22 17:48:07', '2018-03-28 11:41:47', '0');
INSERT INTO `category` VALUES ('15', '0', '冰箱', '0', '1', '2018-03-22 17:48:21', '2018-03-22 17:48:21', '0');
INSERT INTO `category` VALUES ('16', '1', '手机', '0', '1', '2018-03-22 17:50:42', '2018-03-30 13:55:47', '0');
INSERT INTO `category` VALUES ('17', '0', '衣服', '1', '1', '2018-03-23 15:01:04', '2018-03-29 12:40:25', '0');
INSERT INTO `category` VALUES ('18', '1', '彩电', '0', '1', '2018-03-23 15:01:29', '2018-03-30 13:55:57', '0');
INSERT INTO `category` VALUES ('19', '0', '数码', '1', '1', '2018-03-25 16:32:33', '2018-03-26 17:22:38', '0');
INSERT INTO `category` VALUES ('20', '0', '水果', '1', '1', '2018-03-30 14:06:15', '2018-03-30 16:27:03', '0');
INSERT INTO `category` VALUES ('21', '1', 'df', '0', '1', '2018-03-30 14:08:25', '2018-03-30 14:17:00', '1');
INSERT INTO `category` VALUES ('22', '1', '手机', '0', '1', '2018-03-30 14:54:49', '2018-04-02 09:42:52', '0');
INSERT INTO `category` VALUES ('23', '1', 'gd', '0', '1', '2018-03-30 14:54:53', '2018-03-30 14:54:53', '0');
INSERT INTO `category` VALUES ('24', '1', 'r23', '0', '1', '2018-03-30 14:54:57', '2018-03-30 14:54:57', '1');
INSERT INTO `category` VALUES ('25', '1', 'fdf', '0', '1', '2018-03-30 14:55:01', '2018-03-30 14:55:01', '0');
INSERT INTO `category` VALUES ('26', '1', 'jhghj', '0', '1', '2018-03-30 14:55:05', '2018-03-30 14:55:05', '0');
INSERT INTO `category` VALUES ('27', '1', 'rt23324', '0', '1', '2018-03-30 14:55:16', '2018-03-30 14:55:16', '0');
INSERT INTO `category` VALUES ('28', '1', 'fsdaf', '0', '1', '2018-03-30 14:55:20', '2018-03-30 14:55:20', '0');
-- ----------------------------
-- Table structure for collection
-- ----------------------------
DROP TABLE IF EXISTS `collection`;
CREATE TABLE `collection` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`goods_id` int(10) unsigned NOT NULL COMMENT '收藏的商品id.外键,参照goods(id)',
`user_id` int(10) unsigned DEFAULT NULL COMMENT '收藏人id。外键。参照user(id)',
`created` datetime DEFAULT NULL COMMENT '创建时间',
`modify` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of collection
-- ----------------------------
-- ----------------------------
-- Table structure for goods
-- ----------------------------
DROP TABLE IF EXISTS `goods`;
CREATE TABLE `goods` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '商品id',
`title` varchar(255) DEFAULT NULL COMMENT '商品标题',
`sell_point` varchar(255) DEFAULT NULL COMMENT '商品卖点:比如:300减30,500减80,700减100,900减200,抢先加购物车,3月10日0点抢',
`reserve` int(10) unsigned DEFAULT '0' COMMENT '总的库存量。每个款式都有不同的库存',
`pic_url` varchar(500) DEFAULT NULL COMMENT '浏览商品列表时出现的小图片',
`promotion_price` varchar(50) DEFAULT NULL COMMENT '各个款式中的最低促销价。每个款式的商品价格会有差距,比如:10元~100元',
`price` varchar(50) DEFAULT NULL COMMENT '原价。只是吸引顾客的最低价格展示,可以是一段区间。如:10元~100元。真实的价格在款式中',
`style_params` varchar(255) DEFAULT NULL COMMENT '商品属性参数:json字符串形式:[{"param":"颜色","values":["红色","蓝灰色","白色","黑色"]},{"param":"尺码","values":["26","27","28"]}]。二级划分',
`sale_amount` int(10) unsigned DEFAULT NULL COMMENT '总的销量',
`stars` int(10) unsigned DEFAULT NULL COMMENT '收藏量',
`comments` int(10) unsigned DEFAULT NULL COMMENT '商品评价量',
`maker_id` int(10) unsigned DEFAULT NULL COMMENT '创建人id。外键,参照system_user(account)',
`is_delete` tinyint(3) unsigned DEFAULT '0' COMMENT '1删除,0正常',
`is_shelf` tinyint(3) unsigned DEFAULT '0' COMMENT '0下架,1上架',
`created` datetime NOT NULL COMMENT '创建时间',
`modify` datetime NOT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of goods
-- ----------------------------
INSERT INTO `goods` VALUES ('1', 'abc', '50元~100元', '1000', 'http://www.baidu.com', null, '100元', null, '0', '0', '0', '1', '0', '0', '2018-03-13 15:55:13', '2018-03-13 15:55:13');
INSERT INTO `goods` VALUES ('2', 'abc', '50?~100?', '1000', 'http://www.baidu.com', null, '100?', null, '0', '0', '0', '1', '0', '0', '2018-03-13 15:55:13', '2018-03-13 15:55:13');
-- ----------------------------
-- Table structure for goods_cat
-- ----------------------------
DROP TABLE IF EXISTS `goods_cat`;
CREATE TABLE `goods_cat` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '一个商品可能属于多个类型',
`cat_id` int(10) unsigned DEFAULT NULL COMMENT '所属的类型id。外键,参考category(id)',
`goods_id` int(10) unsigned DEFAULT NULL COMMENT '商品id。外键,参考goods(id)',
`created` datetime NOT NULL COMMENT '创建时间',
`modify` datetime DEFAULT NULL COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of goods_cat
-- ----------------------------
-- ----------------------------
-- Table structure for goods_pic
-- ----------------------------
DROP TABLE IF EXISTS `goods_pic`;
CREATE TABLE `goods_pic` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`url` varchar(500) DEFAULT NULL COMMENT '图片的url',
`sort` tinyint(3) unsigned DEFAULT NULL COMMENT '图片的排列顺序。比如在商品图文介绍时:图片的出现是有顺序的',
`cat_id` tinyint(3) unsigned DEFAULT '1' COMMENT '图片类型id。比如:1,作为商品图文展示;2,商品展示的轮播图。',
`goods_id` int(10) unsigned DEFAULT NULL COMMENT '使用该图片的商品id',
`created` datetime DEFAULT NULL COMMENT '创建时间',
`modify` datetime DEFAULT NULL COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of goods_pic
-- ----------------------------
-- ----------------------------
-- Table structure for goods_style
-- ----------------------------
DROP TABLE IF EXISTS `goods_style`;
CREATE TABLE `goods_style` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`goods_id` int(10) unsigned NOT NULL,
`style` text COMMENT '款式的json形式。比如:[{"param":"颜色","value":"红色"},{"param":"尺码","value":"26"}]',
`reserve` int(10) unsigned DEFAULT '0' COMMENT '一个款式的库存量',
`price` float(10,2) DEFAULT NULL COMMENT '一种款式的商品的真实价格',
`specification` text COMMENT '商品的规格参数json形式',
`created` datetime DEFAULT NULL COMMENT '创建时间',
`modify` datetime DEFAULT NULL COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of goods_style
-- ----------------------------
-- ----------------------------
-- Table structure for order
-- ----------------------------
DROP TABLE IF EXISTS `order`;
CREATE TABLE `order` (
`id` int(10) unsigned zerofill NOT NULL AUTO_INCREMENT COMMENT '订单id',
`user_id` int(10) unsigned NOT NULL COMMENT '买家id。外键,参照user(account)',
`address_id` int(10) unsigned NOT NULL COMMENT '买家的收货地址id。外键,参照user_address(id)',
`total_price` float(10,2) DEFAULT '0.00' COMMENT '订单总价格',
`actual_payment` float(10,2) DEFAULT '0.00' COMMENT '实际支付的金额。可能买家用了优惠券',
`pay_method` tinyint(3) DEFAULT '1' COMMENT '付款方式:1系统账户付款,2货到付款,',
`created` datetime NOT NULL COMMENT '下单时间',
`status` tinyint(3) unsigned DEFAULT NULL COMMENT '订单状态:1待付款,2待发货,3待收货,4待评价,5退款/售后,6交易关闭,7交易中,8交易失败',
`pay_time` datetime DEFAULT NULL COMMENT '付款时间',
`ship_time` datetime DEFAULT NULL COMMENT '发货时间',
`deal_time` datetime DEFAULT NULL COMMENT '成交时间',
`express_num` varchar(20) DEFAULT NULL COMMENT '快递单号',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of order
-- ----------------------------
-- ----------------------------
-- Table structure for order_goods
-- ----------------------------
DROP TABLE IF EXISTS `order_goods`;
CREATE TABLE `order_goods` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`order_id` int(10) unsigned DEFAULT NULL COMMENT '订单的id。外键,参照order(id)',
`goods_id` int(10) unsigned DEFAULT NULL COMMENT '订单中的商品id。外键,参照goods(id)',
`goods_style_id` int(10) unsigned DEFAULT NULL COMMENT '一个订单中可以购买各种款式的商品.外键,参照goods_style(id)',
`num` int(10) unsigned DEFAULT NULL COMMENT '购买的商品数量。一款商品购买的数量',
`total_price` float(10,2) DEFAULT NULL COMMENT '一款需要商品的总价,可能有些优惠活动',
`status` tinyint(3) unsigned DEFAULT NULL COMMENT '订单商品状态.1仅退款,2退货退款,3只修不换,4交易成功',
`created` datetime DEFAULT NULL COMMENT '创建时间',
`modify` datetime DEFAULT NULL COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of order_goods
-- ----------------------------
-- ----------------------------
-- Table structure for order_goods_comment
-- ----------------------------
DROP TABLE IF EXISTS `order_goods_comment`;
CREATE TABLE `order_goods_comment` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
`order_goods_id` int(10) unsigned DEFAULT NULL COMMENT '已经购买的商品id。外键,参照order_goods(id)',
`user_id` int(10) unsigned DEFAULT NULL COMMENT '评论人的id,外键,参照user(account)',
`comments` text COMMENT '评论的内容',
`pic_url` varchar(500) DEFAULT NULL COMMENT '评论选填的图片url',
`created` datetime DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of order_goods_comment
-- ----------------------------
-- ----------------------------
-- Table structure for page_content
-- ----------------------------
DROP TABLE IF EXISTS `page_content`;
CREATE TABLE `page_content` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`cat_id` int(10) unsigned DEFAULT NULL COMMENT '类型id。1首页轮播图',
`pic_url` varchar(500) DEFAULT NULL COMMENT '图片的url',
`redirect_url` varchar(500) DEFAULT NULL COMMENT '点击后展示的页面地址',
`title` varchar(255) DEFAULT NULL COMMENT '标题',
`sort` tinyint(3) unsigned DEFAULT NULL COMMENT '相同类型的页面内容根据这个值排序.排列顺序',
`is_release` tinyint(3) unsigned DEFAULT '0' COMMENT '是否发布.0不发布,1发布',
`is_delete` tinyint(3) unsigned DEFAULT NULL COMMENT '0存在,1删除',
`created` datetime DEFAULT NULL COMMENT '创建时间',
`modify` datetime DEFAULT NULL COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of page_content
-- ----------------------------
-- ----------------------------
-- Table structure for shop_cart
-- ----------------------------
DROP TABLE IF EXISTS `shop_cart`;
CREATE TABLE `shop_cart` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '购物车id',
`goods_id` int(10) unsigned NOT NULL COMMENT '添加到购物车中的商品id。外键,参照goods(id)',
`goods_style_id` int(10) unsigned DEFAULT NULL COMMENT '商品的款式id。一个商品在购物车中可以添加多个款式的相同商品。外键,参照goods_style_id(id)',
`user_id` int(10) unsigned DEFAULT NULL COMMENT '买家的账户id。外键,参照user(account)',
`num` tinyint(3) unsigned NOT NULL COMMENT '一次购买商品的数量',
`created` datetime DEFAULT NULL COMMENT '创建时间',
`modify` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of shop_cart
-- ----------------------------
-- ----------------------------
-- Table structure for system_user
-- ----------------------------
DROP TABLE IF EXISTS `system_user`;
CREATE TABLE `system_user` (
`account` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '1管理员,2客服',
`clazz` tinyint(3) unsigned DEFAULT NULL COMMENT '1超级管理员。2客服人员',
`name` varchar(50) DEFAULT NULL COMMENT '用户名',
`phone` varchar(11) DEFAULT NULL COMMENT '手机号',
`pwd` varchar(16) DEFAULT NULL COMMENT '登陆密码',
`money` float(10,2) unsigned DEFAULT NULL COMMENT '该账户上的资金',
`created` datetime DEFAULT NULL COMMENT '创建时间',
`modify` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`account`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of system_user
-- ----------------------------
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`account` int(10) unsigned zerofill NOT NULL AUTO_INCREMENT COMMENT '用户账户',
`name` varchar(20) NOT NULL COMMENT '用户名称',
`pwd` varchar(16) NOT NULL COMMENT '用户密码',
`head_pic` varchar(500) DEFAULT NULL COMMENT '头像的url',
`sex` tinyint(3) unsigned DEFAULT '1' COMMENT '性别:1男,2女',
`phone` varchar(11) NOT NULL COMMENT '用户手机号',
`def_add_id` int(10) unsigned DEFAULT NULL COMMENT '默认的收货地址id。外键,参照user_address(id)',
`money` float(10,2) unsigned DEFAULT NULL COMMENT '该资金用来购买商品。账户上的资产',
`created` datetime NOT NULL COMMENT '账户创建时间',
`modify` datetime DEFAULT NULL COMMENT '信息更新时间',
PRIMARY KEY (`account`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('0000000001', '张三', 'abcdefg', null, '1', '13979198154', null, '0.00', '2018-03-13 11:48:05', '2018-03-13 11:48:05');
INSERT INTO `user` VALUES ('0000000002', '张三', 'abcd', null, '1', '13979198154', null, '0.00', '2018-03-13 11:49:39', '2018-03-13 11:49:39');
-- ----------------------------
-- Table structure for user_address
-- ----------------------------
DROP TABLE IF EXISTS `user_address`;
CREATE TABLE `user_address` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '表的主键。',
`user_id` int(10) unsigned NOT NULL COMMENT '所属的用户id。外键。参照user(account)',
`receiver_name` varchar(20) DEFAULT NULL COMMENT '收件人姓名',
`phone` varchar(11) NOT NULL,
`address` varchar(500) DEFAULT NULL COMMENT '收件地址:包含所在地区(下拉框)+详细地址(文本框)',
`created` datetime NOT NULL COMMENT '创建时间',
`modify` datetime DEFAULT NULL COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user_address
-- ----------------------------
|
-- Lesson 2: Retrieving Data
-- using SELECT statement to retrieve one or more columns
-- retrieving individual columns
SELECT prod_name FROM Products;
-- retrieving multiple columns
SELECT prod_id, prod_name, prod_price FROM Products;
-- retrieving all columns
SELECT * FROM Products;
-- retrieving distinct rows
SELECT vend_id FROM Products; -- versus
SELECT DISTINCT vend_id FROM Products;
-- Limiting results
SELECT prod_name FROM Products LIMIT 5; #returns 5 rows
SELECT prod_name
FROM Products
LIMIT 5 OFFSET 5; #or LIMIT 5,5 (returns 5 rows starting from row 5)
|
CREATE TABLE credential (
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
username VARCHAR(128) NOT NULL COMMENT 'The security principal name/eppn',
password VARCHAR(128) NOT NULL,
enabled BOOLEAN NOT NULL COMMENT 'enabled/disabled status of the security principal',
public_key VARCHAR(1024) NOT NULL,
digital_signature VARCHAR(1024) NOT NULL,
authentication_type VARCHAR(56) NOT NULL COMMENT 'PASSWORD, PKI, ...',
organization_id INT(11) UNSIGNED NOT NULL COMMENT 'foreign key to the organization table',
created_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Created Time',
modified_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Last Updated Time',
PRIMARY KEY (id),
KEY fk_organization_idx (organization_id),
CONSTRAINT fk_credential_organization FOREIGN KEY (organization_id) REFERENCES organization (id)
ON DELETE NO ACTION ON UPDATE NO ACTION
); |
use ge;
drop procedure if exists activate_player;
delimiter //
create procedure activate_player(player_id integer)
begin
declare ship_type_id int;
declare location_object_id int;
declare ship_config_id int;
declare ship_state_id int;
set ship_type_id = (select get_ship_type_id_by_name(get_default_ship_type_name()));
insert into location_object
(location_object_behavior_type_id, location_object_type_id, object_native_id,
location_id, position_x, position_y)
values
(get_location_object_behavior_type_id_by_name('ignored'),
get_location_object_type_id_by_name('player'),
ship_type_id, get_location_id_by_name(get_default_location_name()),
get_default_position_x(), get_default_position_y());
set location_object_id = (select last_insert_id());
insert into ship_config
(ship_config_move_max_speed, ship_config_rotation_max_speed, ship_config_move_acceleration,
ship_config_rotation_acceleration, ship_config_armor, ship_config_energy_max,
ship_config_hp_max, ship_config_energy_regen, ship_config_hp_regen,
ship_type_id, engine_item_id)
values
((select ship_type_move_max_speed
from ship_type st
where st.ship_type_id = ship_type_id),
(select ship_type_rotation_max_speed
from ship_type st
where st.ship_type_id = ship_type_id),
(select ship_type_move_acceleration
from ship_type st
where st.ship_type_id = ship_type_id),
(select ship_type_rotation_acceleration
from ship_type st
where st.ship_type_id = ship_type_id),
(select ship_type_armor
from ship_type st
where st.ship_type_id = ship_type_id),
(select ship_type_energy_max
from ship_type st
where st.ship_type_id = ship_type_id),
(select ship_type_hp_max
from ship_type st
where st.ship_type_id = ship_type_id),
(select ship_type_energy_regen
from ship_type st
where st.ship_type_id = ship_type_id),
(select ship_type_hp_regen
from ship_type st
where st.ship_type_id = ship_type_id),
ship_type_id,
get_item_id_by_name(get_default_engine_name()));
set ship_config_id = (select last_insert_id());
insert into ship_state
(ship_state_hp, ship_state_energy, ship_state_armor_durability)
values
((select ship_type_hp_max
from ship_type st
where st.ship_type_id = ship_type_id),
(select ship_type_energy_max
from ship_type st
where st.ship_type_id = ship_type_id),
(select ship_type_armor_durability
from ship_type st
where st.ship_type_id = ship_type_id));
set ship_state_id = (select last_insert_id());
insert into inventory_item
(amount, item_id, player_id)
values
(get_default_player_money(), get_item_id_by_name('Gold'), player_id);
insert into ship_config_weapon_slot
(ship_config_id, item_id)
values
(ship_config_id, get_item_id_by_name(get_default_weapon_name()));
update player p
set activated = 1, p.location_object_id = location_object_id,
p.ship_config_id = ship_config_id, p.ship_state_id = ship_state_id
where p.player_id = player_id;
end
|
USE myemployees;
#一、查询没有奖金,且工资小于18000的salary, last_name
SELECT
salary,
last_name,
commission_pct
FROM
employees
WHERE
commission_pct IS NULL AND salary<18000;
#二、查询employees表中, job_id不为"IT"或者工资为12000员工信息
SELECT
CONCAT(`first_name`,"-",`last_name`) AS 姓名,
`email` AS 邮件,
`phone_number` AS 电话号码,
`job_id` AS 工作岗位,
`manager_id` AS 工作编号,
`department_id` AS 部门编号,
`hiredate` AS 入职时间
FROM
employees
WHERE
job_id != "IT" OR salary < 12000;
#三、查看部门departments表的结构
DESC departments;
#四、查询部门表中涉及到了哪些位置编号
#distinct是去重的意思
SELECT
DISTINCT location_id AS 位置编号
FROM
departments;
#is null的用法,判断isnull的值时候为null,如果是null则为1,否则为0
SELECT ISNULL(commission_pct) AS 判断的值, commission_pct FROM employees;
|
-- 사원번호를 입력받아 cp_emp2테이블에서 사원번호와 일치하는
-- 사원을 삭제하는 PL/SQL을 작성하세요.
set verify off
set serveroutput on
accept empno prompt '사원번호: '
declare
i_empno cp_emp2.empno%type := &empno;
cnt number;
begin
-- delete의 where절에서는 컬러명과 변수명이 같다면 모두 참으로 판단하여 모든 레코드를 삭제한다.
-- 판단하여 모든 레코드를 삭제한다.
-- 변수명과 컬럼명은 구분될 수 있도록 이름을 설정해야한다.
delete from cp_emp2
where empno = i_empno;
cnt := sql%rowcount;
if cnt = 1 then
dbms_output.put_line(cnt||'건 레코드 삭제');
commit;
else
dbms_output.put_line(cnt||'여러건의 레코드는 삭제할 수 없습니다.');
rollback;
end if;
end;
/ |
-- Trigger that reduces the stock of an item
-- as soon as an order comes through the database
CREATE TRIGGER stock_update
AFTER INSERT on orders
FOR EACH ROW
UPDATE items
SET items.quantity = items.quantity - NEW.number
WHERE items.name = NEW.item_name
|
--COMMANDES A EXECUTER : ------------------------------------------------------------------------------------
--création de la base de donnée
create database bdd;
-- selectionner notre base de donnée
use bdd;
--CREATION DE LA TABLE "membres"
--clé primaire(id) : renseigne l'id d'un membre
--pseudo : renseigne le pseudo de connexion d'un membre
--mail : renseigne le mail d'un membre
--mdp : renseigne le mot de passe de connexion d'un membre
CREATE TABLE membres (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
pseudo VARCHAR(25) NOT NULL,
mail VARCHAR(25) NOT NULL,
mdp CHAR(32) NOT NULL);
--
--
--
--CREATION DE LA TABLE "todolists"
--todolist : renseigne le titre d'une todolist
--status : renseigne le status de la todolist (0 : en cours, 1 : terminé)
--membre : réfèrence à un membre parmit les membres
--clé étrangère(membre) : faire référence à la clé primaire membres(id)
CREATE TABLE todolists (
membre INT NOT NULL,
todolist VARCHAR(100) NOT NULL,
status INT NOT NULL,
FOREIGN KEY(membre) REFERENCES membres(id));
--
--
--
--CREATION DE LA TABLE "taches"
--membre : réfèrence à un membre parmit les membres
--todolist : refère à une todolist parmit les todolists
--tache : renseigne une tache de la todolist
--status : renseigne le status d'une tache (0 : en cours, 1 : terminé)
--clé étrangère(membre) : faire référence à la clé primaire membres(id)
CREATE TABLE taches (
membre INT NOT NULL,
todolist VARCHAR(100) NOT NULL,
tache VARCHAR(255) NOT NULL,
status INT NOT NULL,
FOREIGN KEY(membre) REFERENCES membres(id));
--COMMANDES UTILES : ------------------------------------------------------------------------------------
--list of all tables and views
show tables;
--list of all tables and views with tables types
show full tables;
--description d'une table
describe membres;
--voir tous les utilisateurs
select * from membres;
--voir toutes les todolists
select * from todolists;
--voir toutes les taches
select * from taches;
--COMMANDES AUTRES : ------------------------------------------------------------------------------------
--ajouter une colonne :
ALTER TABLE nom_table
ADD nom_colonne type_donnees
--supprimer une colonne :
ALTER TABLE nom_table
DROP nom_colonne
--modifier une colonne:
ALTER TABLE nom_table
MODIFY nom_colonne type_donnees
--renommer une colonne :
ALTER TABLE nom_table
CHANGE colonne_ancien_nom colonne_nouveau_nom type_donnees
--ajouter des valeurs (colonne) :
INSERT INTO nom_table (nom_colonne_1, nom_colonne_2, ...)
VALUES ('valeur 1', 'valeur 2', ...)
--exemple :
--ajouter des membres
INSERT INTO membres (pseudo, mail, mdp) VALUES ("alex", "alexandre@supinfo.com", md5("ZITOUNI"));
INSERT INTO membres (pseudo, mail, mdp) VALUES ("tom", "thomas@supinfo.com", md5("SENSE"));
--ajouter des todolists
INSERT INTO todolists (membre, todolist, status) VALUES (1, "Faire les courses", 0);
INSERT INTO todolists (membre, todolist, status) VALUES (2, "Planning", 0);
--ajouter des taches
INSERT INTO taches (membre, todolist, tache, status) VALUES (1, "Faire les courses", "pommes", 0);
INSERT INTO taches (membre, todolist, tache, status) VALUES (1, "Faire les courses", "poires", 0);
INSERT INTO taches (membre, todolist, tache, status) VALUES (1, "Faire les courses", "orange", 0);
INSERT INTO taches (membre, todolist, tache, status) VALUES (2, "Planning", "courir", 0);
INSERT INTO taches (membre, todolist, tache, status) VALUES (2, "Planning", "travailler", 0);
INSERT INTO taches (membre, todolist, tache, status) VALUES (2, "Planning", "dormir", 0);
--mettre à jour une ligne :
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
--exemple, changer le détenteur d'une todolist :
UPDATE todolists SET membre = 2 WHERE todolist="Planning";
UPDATE taches SET membre = 2 WHERE todolist = "Planning";
--supprimer une ligne :
DELETE FROM nom_table WHERE condition;
--exemple, supprimer un membre :
DELETE FROM membres WHERE pseudo="alick";
--exemple, supprimer une todolist :
DELETE FROM todolists WHERE todolist="todo_name";
--supprimer une table :
DROP TABLE nom_table;
--reset l'auto increment :
SELECT MAX( `id` ) FROM `membres` ; -- selectionne l'id max
ALTER TABLE `membres` AUTO_INCREMENT = number; -- // ou réinitialisation => 0 |
create database shop;
use shop;
create table Jyushoroku
(
toroku_bango integer not null,
name varchar(128) not null,
jyusho varchar(256) not null,
tel_no char(10),
mail_address char(20),
primary key (toroku_bango)
);
alter table Jyushoroku add column yubin_bango char(8) not null; |
CREATE DATABASE books;
USE books;
CREATE TABLE authors(
au_id char(3),
au_fname VARCHAR(15) NOT NULL,
au_lname VARCHAR(15) NOT NULL,
phone VARCHAR(15),
[address] VARCHAR(20),
city VARCHAR(10),
[state] VARCHAR(15),
zip VARCHAR(15),
CONSTRAINT PK_AU_ID PRIMARY KEY (au_id)
);
INSERT INTO books.dbo.authors(au_id,au_fname,au_lname,phone,[address],city,[state],zip)
VALUES('A01','victor','burtsev','0671635318','mate zalki 8a','kiev','Uk','04211');
INSERT INTO books.dbo.authors(au_id,au_fname,au_lname,phone,[address],city,[state],zip)
VALUES('A02','rita','kostrova','0676675357','mate zalki 8a','kiev','Uk','04211');
INSERT INTO books.dbo.authors(au_id,au_fname,au_lname,phone,[address],city,[state],zip)
VALUES('A03','andre','pilchevskiy','067558846','proizernay 9g','London','AL','56911');
CREATE TABLE publishers(
pub_id char(3),
pub_name VARCHAR(45) NOT NULL,
city VARCHAR(40) NOT NULL,
[state] VARCHAR(15),
country VARCHAR(15) NOT NULL,
CONSTRAINT PK_PU_ID PRIMARY KEY (pub_id)
);
INSERT INTO books.dbo.publishers(pub_id,pub_name,city,[state],country)
VALUES('P01','Gramen Budgovy','Lviv','Lu','Uk');
INSERT INTO books.dbo.publishers(pub_id,pub_name,city,[state],country)
VALUES('P02','Aremenko Dlabimir','Poltava','Pu','Uk');
INSERT INTO books.dbo.publishers(pub_id,pub_name,city,[state],country)
VALUES('P03','Kovalchuk Vania','New Yourk','NY','USA');
CREATE TABLE titles(
title_id char(3),
title_name VARCHAR(40),
[type] VARCHAR(35) NOT NULL,
pub_id CHAR(3),
pages INT,
price DECIMAL(5,2),
sales INT,
pubdate DATE,
[contract] SMALLINT NOT NULL,
CONSTRAINT PK_TI_ID PRIMARY KEY (title_id),
CONSTRAINT FK_TITLE_ID FOREIGN KEY (pub_id) REFERENCES publishers (pub_id)
);
INSERT INTO books.dbo.titles(title_id,title_name,[type],pub_id,pages,price,sales,pubdate,[contract])
VALUES('T01','Orson Framework','information Literatyre','P01',301,100.2,566,'2015-12-11',1);
INSERT INTO books.dbo.titles(title_id,title_name,[type],pub_id,pages,price,sales,pubdate,[contract])
VALUES('T02','Hitanka 4cls','history','P02',204,400.9,20,'2009-11-09',0);
INSERT INTO books.dbo.titles(title_id,title_name,[type],pub_id,pages,price,sales,pubdate,[contract])
VALUES('T03','html+css','web','P03',503,120.1,56,'2015-01-03',1);
CREATE TABLE titles_authors(
au_id char(3),
title_id char(3),
au_order SMALLINT NOT NULL,
roaylty_share DECIMAL(5,2) NOT NULL,
/*PRIMARY KEY (au_id),*/CONSTRAINT FK_AU_ID FOREIGN KEY (au_id) REFERENCES authors (au_id),
/*PRIMARY KEY (au_id),*/CONSTRAINT FK_TITLE_AUTH_ID FOREIGN KEY (title_id) REFERENCES titles (title_id)
);
INSERT INTO books.dbo.titles_authors(au_id,title_id,au_order,roaylty_share)
VALUES('A01','T01',1,1.0);
INSERT INTO books.dbo.titles_authors(au_id,title_id,au_order,roaylty_share)
VALUES('A01','T03',2,0.3);
INSERT INTO books.dbo.titles_authors(au_id,title_id,au_order,roaylty_share)
VALUES('A01','T02',2,0.5);
INSERT INTO books.dbo.titles_authors(au_id,title_id,au_order,roaylty_share)
VALUES('A02','T02',1,0.5);
INSERT INTO books.dbo.titles_authors(au_id,title_id,au_order,roaylty_share)
VALUES('A03','T03',1,0.3);
INSERT INTO books.dbo.titles_authors(au_id,title_id,au_order,roaylty_share)
VALUES('A02','T03',3,0.3);
CREATE TABLE royalties(
title_id char(3),
advance DECIMAL(9,2),
roaylty_rate DECIMAL(5,2) NOT NULL,
/*PRIMARY KEY (title_id),*/ CONSTRAINT FK_ROYALTIES_ID FOREIGN KEY (title_id) REFERENCES titles (title_id)
);
INSERT INTO books.dbo.royalties(title_id,advance,roaylty_rate)
VALUES('T01',1000,0.5);
INSERT INTO books.dbo.royalties(title_id,advance,roaylty_rate)
VALUES('T02',1020,0.09);
INSERT INTO books.dbo.royalties(title_id,advance,roaylty_rate)
VALUES('T01',25.6,0.015);
|
DROP DATABASE vzw_test;
CREATE DATABASE vzw_test;
USE vzw_test;
-- -----------------------------------------------------
-- Table `vzw_test`.`City`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vzw_test`.`City` (
`idCity` INT(11) NOT NULL AUTO_INCREMENT,
`postCode` VARCHAR(20) NOT NULL,
`name` VARCHAR(100) NOT NULL,
PRIMARY KEY (`idCity`))
ENGINE = InnoDB
AUTO_INCREMENT = 2
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `vzw_test`.`Address`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vzw_test`.`Address` (
`idAddress` INT NOT NULL AUTO_INCREMENT,
`address` VARCHAR(100) NOT NULL,
`fk_City` INT(11) NOT NULL,
PRIMARY KEY (`idAddress`),
INDEX `fk_Address_City_idx` (`fk_City` ASC),
CONSTRAINT `fk_Address_City`
FOREIGN KEY (`fk_City`)
REFERENCES `vzw_test`.`City` (`idCity`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
USE `vzw_test` ;
-- -----------------------------------------------------
-- Table `vzw_test`.`User`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vzw_test`.`User` (
`idUser` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`surname` VARCHAR(45) NOT NULL,
`email` VARCHAR(100) NOT NULL,
`birthDate` DATE NOT NULL,
`gender` VARCHAR(1) NOT NULL,
`phone` VARCHAR(50) NOT NULL,
`fk_Address` INT NOT NULL,
PRIMARY KEY (`idUser`),
INDEX `fk_User_Address1_idx` (`fk_Address` ASC),
CONSTRAINT `fk_User_Address1`
FOREIGN KEY (`fk_Address`)
REFERENCES `vzw_test`.`Address` (`idAddress`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `vzw_test`.`Client`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vzw_test`.`Client` (
`idClient` INT(11) NOT NULL AUTO_INCREMENT,
`fk_User` INT(11) NOT NULL,
PRIMARY KEY (`idClient`),
INDEX `fk_kunde_user1_idx` (`fk_User` ASC),
CONSTRAINT `fk_Client_User`
FOREIGN KEY (`fk_User`)
REFERENCES `vzw_test`.`User` (`idUser`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `vzw_test`.`Category`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vzw_test`.`Category` (
`idCategory` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`minAge` INT(11) NOT NULL,
`maxAge` INT(11) NOT NULL,
PRIMARY KEY (`idCategory`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `vzw_test`.`Course`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vzw_test`.`Course` (
`idCourse` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`fk_Category` INT(11) NOT NULL,
`weekday` VARCHAR(45) NOT NULL,
`startate` DATE NOT NULL,
`enddate` DATE NOT NULL,
`starttime` TIME NOT NULL,
`endtime` TIME NOT NULL,
`cancellationDates` VARCHAR(100) NOT NULL,
`lessonNumber` INT(11) NOT NULL,
`costs` INT(11) NOT NULL,
`maxRegistration` INT(11) NOT NULL,
PRIMARY KEY (`idCourse`),
INDEX `fk_kurs_kategorie1_idx` (`fk_Category` ASC),
CONSTRAINT `fk_Course_Category`
FOREIGN KEY (`fk_Category`)
REFERENCES `vzw_test`.`Category` (`idCategory`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `vzw_test`.`Cancellation`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vzw_test`.`Cancellation` (
`idCancellation` INT(11) NOT NULL AUTO_INCREMENT,
`Client_idClient` INT(11) NOT NULL,
`Course_idCourse` INT(11) NOT NULL,
PRIMARY KEY (`idCancellation`),
INDEX `fk_Cancellation_Client1_idx` (`Client_idClient` ASC),
INDEX `fk_Cancellation_Course1_idx` (`Course_idCourse` ASC),
CONSTRAINT `fk_Cancellation_Client`
FOREIGN KEY (`Client_idClient`)
REFERENCES `vzw_test`.`Client` (`idClient`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Cancellation_Course`
FOREIGN KEY (`Course_idCourse`)
REFERENCES `vzw_test`.`Course` (`idCourse`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `vzw_test`.`EventInformation`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vzw_test`.`EventInformation` (
`idEventInformation` INT(11) NOT NULL AUTO_INCREMENT,
`startdate` DATE NOT NULL,
`enddate` DATE NOT NULL,
`name` VARCHAR(100) NOT NULL,
`links` VARCHAR(500) NOT NULL,
PRIMARY KEY (`idEventInformation`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `vzw_test`.`Competition`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vzw_test`.`Competition` (
`idCompetition` INT(11) NOT NULL AUTO_INCREMENT,
`fk_EventInformation` INT(11) NOT NULL,
`category` VARCHAR(100) NOT NULL,
PRIMARY KEY (`idCompetition`),
INDEX `fk_Competition_EventInformation1_idx` (`fk_EventInformation` ASC),
CONSTRAINT `fk_Competition_EventInformation1`
FOREIGN KEY (`fk_EventInformation`)
REFERENCES `vzw_test`.`EventInformation` (`idEventInformation`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `vzw_test`.`Event`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vzw_test`.`Event` (
`idEvent` INT(11) NOT NULL AUTO_INCREMENT,
`fk_EventInformation` INT(11) NOT NULL,
`description` VARCHAR(255) NOT NULL,
PRIMARY KEY (`idEvent`),
INDEX `fk_Event_EventInformation1_idx` (`fk_EventInformation` ASC),
CONSTRAINT `fk_Event_EventInformation1`
FOREIGN KEY (`fk_EventInformation`)
REFERENCES `vzw_test`.`EventInformation` (`idEventInformation`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `vzw_test`.`Member`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vzw_test`.`Member` (
`idMember` INT(11) NOT NULL AUTO_INCREMENT,
`fk_User` INT(11) NOT NULL,
`username` VARCHAR(100) NOT NULL,
`password` VARCHAR(100) NOT NULL,
PRIMARY KEY (`idMember`),
INDEX `fk_mitglied_user1_idx` (`fk_User` ASC),
CONSTRAINT `fk_Member_User`
FOREIGN KEY (`fk_User`)
REFERENCES `vzw_test`.`User` (`idUser`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `vzw_test`.`Registration`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vzw_test`.`Registration` (
`idRegistration` INT(11) NOT NULL AUTO_INCREMENT,
`fk_Client` INT(11) NOT NULL,
`fk_Course` INT(11) NOT NULL,
`status` INT(11) NOT NULL,
PRIMARY KEY (`idRegistration`),
INDEX `fk_Registration_Client1_idx` (`fk_Client` ASC),
INDEX `fk_Registration_Course1_idx` (`fk_Course` ASC),
CONSTRAINT `fk_Registration_Client`
FOREIGN KEY (`fk_Client`)
REFERENCES `vzw_test`.`Client` (`idClient`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Registration_Course`
FOREIGN KEY (`fk_Course`)
REFERENCES `vzw_test`.`Course` (`idCourse`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
|
https://platform.stratascratch.com/coding-question?id=9924&python=
select home_library_code from library_usage
where circulation_active_year = 2016
and provided_email_address = false
and notice_preference_definition = 'email'; |
CREATE FUNCTION [macro].[Configuracion]
()
RETURNS TABLE
AS
RETURN
(
SELECT
a.id_plantilla AS PLANTILLA
,a.alias AS CAMPO
,a.longitud AS [NUMERO MAX CARACTERES]
,CASE WHEN a.requerido = 0 THEN 'N' ELSE 'S' END AS REQUERIDO
,a.valor_predeterminado AS [VALOR PREDETERMINADO]
,a.valores_permitidos AS [LISTA DE VALORES PERMITIDOS]
,COALESCE(CAST(a.valor_minimo AS VARCHAR),'') AS [VALOR MINIMO]
,COALESCE(CAST(a.valor_maximo AS VARCHAR),'') AS [VALOR MAXIMO]
,a.ordinal AS [ORDEN]
FROM macro.plantillas a
)
|
-- Adminer 4.7.8 MySQL dump
SET NAMES utf8;
SET time_zone = '+00:00';
SET foreign_key_checks = 0;
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
CREATE DATABASE `blog` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `blog`;
DROP TABLE IF EXISTS `authors`;
CREATE TABLE `authors` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`firstname` varchar(45) DEFAULT NULL,
`nickname` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `nickname_UNIQUE` (`nickname`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `authors` (`id`, `name`, `firstname`, `nickname`) VALUES
(1, 'Smith', 'Bob', 'Matéo'),
(2, 'Apple', 'Jim', 'yoyo35'),
(3, 'Roger', 'Bill', 'billy'),
(4, 'Pristy', 'Valentina', 'Valentine'),
(7, 'Denver', 'Matt', 'matthew'),
(8, 'Bron', 'Anna', 'banana58');
DROP TABLE IF EXISTS `categories`;
CREATE TABLE `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `categories` (`id`, `name`) VALUES
(2, 'Loisirs'),
(3, 'Actus');
DROP TABLE IF EXISTS `categories_has_posts`;
CREATE TABLE `categories_has_posts` (
`categories_id` int(11) NOT NULL,
`posts_id` int(11) NOT NULL,
PRIMARY KEY (`categories_id`,`posts_id`),
KEY `fk_categories_has_posts_posts1_idx` (`posts_id`),
KEY `fk_categories_has_posts_categories_idx` (`categories_id`),
CONSTRAINT `fk_categories_has_posts_categories` FOREIGN KEY (`categories_id`) REFERENCES `categories` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_categories_has_posts_posts1` FOREIGN KEY (`posts_id`) REFERENCES `posts` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `categories_has_posts` (`categories_id`, `posts_id`) VALUES
(2, 1),
(2, 2),
(3, 3),
(3, 4);
DROP TABLE IF EXISTS `comments`;
CREATE TABLE `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`text` varchar(150) NOT NULL,
`date` datetime NOT NULL DEFAULT current_timestamp(),
`authors_id` int(11) NOT NULL,
`posts_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_comments_authors1_idx` (`authors_id`),
KEY `fk_comments_posts1_idx` (`posts_id`),
CONSTRAINT `fk_comments_authors1` FOREIGN KEY (`authors_id`) REFERENCES `authors` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_comments_posts1` FOREIGN KEY (`posts_id`) REFERENCES `posts` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `comments` (`id`, `text`, `date`, `authors_id`, `posts_id`) VALUES
(1, 'Bravo !', '2021-01-21 11:49:10', 8, 1),
(2, 'Sans avis', '2021-01-21 11:49:10', 4, 2),
(3, 'Reflexion...', '2021-01-21 11:51:05', 1, 2),
(4, 'La vérité fait mal', '2021-01-21 11:56:14', 4, 3),
(5, '!!!!!!', '2021-01-21 11:56:14', 7, 4);
DROP TABLE IF EXISTS `posts`;
CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(45) NOT NULL,
`text` varchar(150) NOT NULL,
`date_begin` datetime NOT NULL,
`date_end` datetime NOT NULL,
`important` int(11) NOT NULL DEFAULT 0,
`authors_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_posts_authors1_idx` (`authors_id`),
CONSTRAINT `fk_posts_authors1` FOREIGN KEY (`authors_id`) REFERENCES `authors` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `posts` (`id`, `title`, `text`, `date_begin`, `date_end`, `important`, `authors_id`) VALUES
(1, 'Le sport c\'est la vie', 'Le sport c\'est vraiment génial les gars ! Notamment le Biathlon !', '2021-01-21 11:46:36', '2021-02-28 11:44:05', 5, 8),
(2, 'La petanque est il vraiment un sport ?', 'C\'est une excellente question qui mérite réflexion.', '2021-01-21 11:46:36', '2021-01-30 11:44:05', 1, 1),
(3, 'La politique française est elle corrompu ?', 'Nous connaissons déjà la réponse à cette problématique.', '2021-01-21 11:55:06', '2021-01-31 11:51:28', 4, 2),
(4, 'Comment Macron a t-il pu devenir président', 'Je vous réfère à l\'article concernant la corruption en France dans le milieu politique Francais', '2021-01-21 11:55:06', '2021-02-06 11:51:28', 3, 3);
-- 2021-01-25 10:40:13
|
-- phpMyAdmin SQL Dump
-- version 3.3.5
-- http://www.phpmyadmin.net
--
-- Servidor: 127.0.0.1
-- Temps de generació: 20-01-2017 a les 16:35:07
-- Versió del servidor: 5.1.49
-- Versió de PHP : 5.3.3
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Base de dades: `frankfurt`
--
-- --------------------------------------------------------
--
-- Estructura de la taula `comanda`
--
CREATE TABLE IF NOT EXISTS `comanda` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`taula_id` int(11) NOT NULL,
`actiu` tinyint(1) NOT NULL DEFAULT '1',
`preu_final` decimal(10,2) DEFAULT NULL,
`data_pagament` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=23 ;
--
-- Bolcant dades de la taula `comanda`
--
INSERT INTO `comanda` (`id`, `taula_id`, `actiu`, `preu_final`, `data_pagament`) VALUES
(1, 1, 0, 20.00, '2017-01-06 12:43:01'),
(2, 3, 0, 23.50, '2017-01-06 20:30:32'),
(3, 2, 0, 3.50, '2017-01-12 15:39:07'),
(10, 1, 0, 17.00, '2017-01-11 17:44:18'),
(11, 1, 0, 2.00, '2017-01-12 15:39:15'),
(12, 3, 0, 3.50, '2017-01-12 15:39:19'),
(13, 4, 0, 3.50, '2017-01-12 15:39:23'),
(14, 5, 0, 3.50, '2017-01-12 15:39:27'),
(15, 6, 0, 3.50, '2017-01-12 15:39:31'),
(16, 1, 0, 3.50, '2017-01-12 15:40:01'),
(17, 2, 0, 3.50, '2017-01-12 15:40:05'),
(18, 1, 0, 3.50, '2017-01-12 15:43:45'),
(19, 2, 0, 25.50, '2017-01-13 16:33:25'),
(20, 5, 0, 18.50, '2017-01-18 16:42:53'),
(21, 1, 1, NULL, NULL),
(22, 2, 1, NULL, NULL);
-- --------------------------------------------------------
--
-- Estructura de la taula `detall`
--
CREATE TABLE IF NOT EXISTS `detall` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`producte_id` int(11) NOT NULL,
`preu` decimal(10,2) NOT NULL,
`comanda_id` int(11) NOT NULL,
`estat` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=63 ;
--
-- Bolcant dades de la taula `detall`
--
INSERT INTO `detall` (`id`, `producte_id`, `preu`, `comanda_id`, `estat`) VALUES
(3, 1, 3.00, 1, 2),
(4, 1, 3.00, 1, 2),
(5, 2, 4.00, 2, 2),
(6, 3, 1.00, 1, 2),
(10, 2, 5.50, 1, 2),
(11, 1, 3.50, 1, 2),
(12, 5, 2.00, 1, 2),
(13, 6, 2.00, 1, 2),
(14, 1, 5.50, 2, 2),
(15, 1, 3.50, 2, 2),
(16, 1, 3.50, 2, 2),
(17, 1, 3.50, 2, 2),
(18, 1, 3.50, 2, 2),
(25, 1, 3.50, 10, 2),
(26, 1, 3.50, 10, 2),
(29, 1, 3.50, 10, 2),
(30, 2, 5.50, 10, 2),
(31, 3, 1.00, 10, 2),
(32, 6, 2.00, 11, 2),
(33, 1, 3.50, 3, 2),
(34, 1, 3.50, 12, 2),
(35, 1, 3.50, 13, 2),
(36, 1, 3.50, 14, 2),
(37, 1, 3.50, 15, 2),
(38, 1, 3.50, 16, 2),
(39, 1, 3.50, 17, 2),
(40, 1, 3.50, 18, 2),
(41, 1, 3.50, 19, 2),
(42, 1, 3.50, 19, 2),
(43, 1, 3.50, 19, 2),
(44, 5, 2.00, 20, 2),
(45, 5, 2.00, 20, 2),
(46, 5, 2.00, 20, 2),
(47, 6, 2.00, 20, 2),
(48, 2, 5.50, 19, 2),
(49, 2, 5.50, 19, 2),
(50, 6, 2.00, 19, 2),
(51, 6, 2.00, 19, 2),
(52, 1, 3.50, 20, 2),
(53, 1, 3.50, 20, 2),
(54, 1, 3.50, 20, 2),
(55, 1, 3.50, 21, 1),
(56, 1, 3.50, 21, 1),
(57, 1, 3.50, 22, 1),
(58, 5, 2.00, 22, 0),
(59, 1, 3.50, 21, 1),
(60, 3, 1.00, 21, 2),
(61, 1, 3.50, 21, 0),
(62, 1, 3.50, 21, 0);
-- --------------------------------------------------------
--
-- Estructura de la taula `ordre`
--
CREATE TABLE IF NOT EXISTS `ordre` (
`detall_id` int(11) NOT NULL,
`ordre` int(11) NOT NULL,
PRIMARY KEY (`detall_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Bolcant dades de la taula `ordre`
--
INSERT INTO `ordre` (`detall_id`, `ordre`) VALUES
(58, 3),
(61, 1),
(62, 2);
-- --------------------------------------------------------
--
-- Estructura de la taula `usuari`
--
CREATE TABLE IF NOT EXISTS `usuari` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(32) NOT NULL,
`nom` varchar(32) NOT NULL,
`cognoms` varchar(32) NOT NULL,
`pass` varchar(32) NOT NULL,
`cambrer` tinyint(1) NOT NULL DEFAULT '0',
`cuiner` tinyint(1) NOT NULL DEFAULT '0',
`cobrar` tinyint(1) NOT NULL DEFAULT '0',
`recuperar` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
--
-- Bolcant dades de la taula `usuari`
--
INSERT INTO `usuari` (`id`, `email`, `nom`, `cognoms`, `pass`, `cambrer`, `cuiner`, `cobrar`, `recuperar`) VALUES
(1, 'admin', 'admin', 'admin', '81dc9bdb52d04dc20036dbd8313ed055', 0, 0, 0, NULL),
(2, 'w2.jferre@infomila.info', 'Joan', 'Ferré', '81dc9bdb52d04dc20036dbd8313ed055', 1, 1, 1, '67d3d4c4dd0b82eee951af73f9f33e3c'),
(3, 'jofe93@gmail.com', 'asd', 'qwe', '81dc9bdb52d04dc20036dbd8313ed055', 0, 0, 1, '7a680364b943137b7042d68fa3b2e687');
|
SELECT lives_ok($$SELECT crypto_pwhash_saltgen()$$, 'crypto_pwhash_saltgen');
SELECT is(crypto_pwhash('Correct Horse Battery Staple', '\xccfe2b51d426f88f6f8f18c24635616b'),
'\x77d029a9b3035c88f186ed0f69f58386ad0bd5252851b4e89f0d7057b5081342',
'crypto_pwhash');
select throws_ok($$select crypto_pwhash(NULL, 'bad')$$,
'22000', 'pgsodium_crypto_pwhash: data cannot be NULL', 'crypto_pwhash NULL password');
select throws_ok($$select crypto_pwhash('bad', NULL)$$,
'22000', 'pgsodium_crypto_pwhash: salt cannot be NULL', 'crypto_pwhash NULL salt');
SELECT ok(crypto_pwhash_str_verify(crypto_pwhash_str('Correct Horse Battery Staple'),
'Correct Horse Battery Staple'),
'crypto_pwhash_str_verify');
select throws_ok($$select crypto_pwhash_str(NULL)$$,
'22000', 'pgsodium_crypto_pwhash_str: password cannot be NULL', 'crypto_pwhash_str NULL password');
select throws_ok($$select crypto_pwhash_str_verify(NULL, 'bad')$$,
'22000', 'pgsodium_crypto_pwhash_str_verify: hashed password cannot be NULL', 'crypto_pwhash_str_verify NULL hash');
select throws_ok($$select crypto_pwhash_str_verify('bad', NULL)$$,
'22000', 'pgsodium_crypto_pwhash_str_verify: password cannot be NULL', 'crypto_pwhash_str_verify NULL password');
|
--
-- Migration file: "changes_in_pizzas_list" created at 13.02.2015 14:56:29 (+05:00)
--
INSERT INTO `pizzas` (`id`, `title`, `description`, `url`, `image_url_large`, `image_url_medium`, `image_url_small`, `price`, `hidden`) VALUES
(29, 'Сливочный бекон', 'Бекон, сыры Моцарелла и Пармезан, оливки, красный лук и сливки.', 'http://www.eda1.ru/6/37/190/2482', 'http://www.eda1.ru/upload/images/7592f.jpg', 'http://www.eda1.ru/upload/images/7592m.jpg', 'http://www.eda1.ru/upload/images/7592.jpg', 385, 0),
(30, 'Сырная', 'Очень просто и очень вкусно: сливки, сыры Моцарелла и Пармезан.', 'http://www.eda1.ru/6/37/190/2482', 'http://www.eda1.ru/upload/images/6016f.jpg', 'http://www.eda1.ru/upload/images/6016m.jpg', 'http://www.eda1.ru/upload/images/6016.jpg', 235, 0);
UPDATE `pizzas` SET `hidden` = 1 WHERE `id` IN (1, 3, 17);
|
/*******************************************************************************
** File Name: Sustainable Technology Database Data Definition Language
** Author: Matt Byrne and Thanh Nguyen
** Date: 3/17/2019
** Description: This file contains the SQL queries for creating the
** Sustainable Technology Database in MySQL and inserting sample data
** according to the requirements set forth in the Project Guide.
*******************************************************************************/
/*if tables already exist in database, delete them*/
DROP TABLE IF EXISTS `EnergyTechnology`;
DROP TABLE IF EXISTS `Energy_Region`;
DROP TABLE IF EXISTS `Energy_Company`;
DROP TABLE IF EXISTS `Company_Product`;
DROP TABLE IF EXISTS `EnergySource`;
DROP TABLE IF EXISTS `Company`;
DROP TABLE IF EXISTS `SustainableProduct`;
DROP TABLE IF EXISTS `Region`;
/*create the eight tables that constitute the database*/
CREATE TABLE `EnergySource` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`percent_global_power` int(3),
`annual_growth` int(3),
`cost_per_kWh` int(11),
PRIMARY KEY (`id`),
CONSTRAINT `chk_percent_global` CHECK ((percent_global_power >= 0 AND
percent_global_power <= 100) OR percent_global_power IS NULL),
CONSTRAINT `chk_growth` CHECK ((annual_growth >= 0 AND
annual_growth <= 100) OR annual_growth IS NULL),
CONSTRAINT `chk_cost` CHECK ((cost_per_kWh > 0) OR cost_per_kWh IS NULL)
) ENGINE = InnoDB;
CREATE TABLE `EnergyTechnology` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`cost_per_watt` float(4, 2),
`development_stage` varchar(20) DEFAULT 'Theoretical',
`energy_src_id` int(11),
PRIMARY KEY (`id`),
CONSTRAINT `chk_cost_per` CHECK (cost_per_watt > 0 OR cost_per_watt IS NULL),
CONSTRAINT `chk_dev_stage` CHECK (development_stage = 'Theoretical' OR
development_stage = "Experimental" OR development_stage = "Pilot-stage" OR
development_stage = "Commercial" OR development_stage = "Utility-scale"),
CONSTRAINT `EnergyTechnology_fk` FOREIGN KEY (`energy_src_id`) REFERENCES
`EnergySource` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB;
CREATE TABLE `Company` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`annual_revenue` int(11),
`annual_growth` int(20),
PRIMARY KEY (`id`),
CONSTRAINT `chk_rev` CHECK (annual_revenue >= 0 OR annual_revenue IS NULL)
) ENGINE = InnoDB;
CREATE TABLE `SustainableProduct` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`cost_per_unit` int(11),
`sector` varchar(50),
PRIMARY KEY (`id`),
CONSTRAINT `chk_cost_unit` CHECK (cost_per_unit >= 0 OR cost_per_unit IS NULL)
) ENGINE = InnoDB;
CREATE TABLE `Region` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`population` int(11),
`country` varchar(50) NOT NULL,
`continent` varchar(20),
PRIMARY KEY (`id`),
CONSTRAINT `chk_continent` CHECK (continent = 'Africa' OR continent =
'Antarctica' OR continent = 'Asia' OR continent = 'Australia' OR continent
= 'Europe' OR continent = 'North America' OR continent = 'Oceania' OR
continent = 'South America')
) ENGINE = InnoDB;
CREATE TABLE `Energy_Region` (
`energy_src_id` int(11) NOT NULL,
`region_id` int(11) NOT NULL,
PRIMARY KEY (`energy_src_id`, `region_id`),
CONSTRAINT `energy_fk1` FOREIGN KEY (`energy_src_id`) REFERENCES `EnergySource` (`id`) ON DELETE CASCADE,
CONSTRAINT `region_fk` FOREIGN KEY (`region_id`) REFERENCES `Region` (`id`) ON DELETE CASCADE
) ENGINE = InnoDB;
CREATE TABLE `Energy_Company` (
`energy_src_id` int(11) NOT NULL,
`company_id` int(11) NOT NULL,
PRIMARY KEY (`energy_src_id`, `company_id`),
CONSTRAINT `energy_fk2` FOREIGN KEY (`energy_src_id`) REFERENCES `EnergySource` (`id`) ON DELETE CASCADE,
CONSTRAINT `company_fk1` FOREIGN KEY (`company_id`) REFERENCES `Company` (`id`) ON DELETE CASCADE
) ENGINE = InnoDB;
CREATE TABLE `Company_Product` (
`company_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
PRIMARY KEY (`company_id`, `product_id`),
CONSTRAINT `company_fk2` FOREIGN KEY (`company_id`) REFERENCES `Company` (`id`) ON DELETE CASCADE,
CONSTRAINT `product_fk` FOREIGN KEY (`product_id`) REFERENCES `SustainableProduct` (`id`) ON DELETE CASCADE
) ENGINE = InnoDB;
/*code for dropping table if already found in database sourced from:
https://stackoverflow.com/questions/7887011/how-to-drop-a-table-if-it-exists-in-sql-server/33497857#33497857
code for using constraints to restrict value input sourced from:
https://stackoverflow.com/questions/2441427/restrict-varchar-column-to-specific-values
--code for creating many-to-many relationship tables sourced from:
--https://stackoverflow.com/questions/260441/how-to-create-relationships-in-mysql*/
/*insert sample data into the database*/
INSERT INTO `EnergySource` (`name`, `percent_global_power`, `annual_growth`, `cost_per_kWh`)
VALUES ('Solar', 7, 34, 7);
--percent_global_power figure sourced from:
--https://www.c2es.org/content/renewable-energy/
--annual growth figure sourced from:
--http://www.iea-pvps.org/fileadmin/dam/public/report/statistics/IEA-PVPS_-_A_Snapshot_of_Global_PV_-_1992-2016__1_.pdf
--cost_per_kWh figure sourced from:
--https://www.solar-estimate.org/news/2018-03-08-how-are-solar-panels-changing-america
INSERT INTO `EnergyTechnology` (`name`, `development_stage`, `cost_per_watt`, `energy_src_id`)
VALUES ('Photovoltaic Array', 'Commercial', 3, 1);
--cost_per_watt figure sourced from:
--https://news.energysage.com/3-kw-solar-panel-systems-prices-installers/
INSERT INTO `Company` (`name`, `annual_revenue`, `annual_growth`)
VALUES ('SolarCity', 730000000, 30);
--annual_revenue figure sourced from:
--https://csimarket.com/stocks/single_growth_rates.php?code=SCTY&rev
--annual_growth figures sourced from:
--https://www.forbes.com/sites/greatspeculations/2018/09/25/two-years-in-teslas-solarcity-deal-looks-increasingly-like-a-bad-bet/#79108d7e877f
INSERT INTO `SustainableProduct` (`name`, `cost_per_unit`, `sector`)
VALUES ('Home Battery', 3400, 'Household Consumer Product');
--cost_per_unit figure sourced from:
--https://www.solar-estimate.org/news/2018-03-12-is-the-tesla-powerwall-2-worth-buying-and-how-it-compares-to-other-storage
INSERT INTO `Region` (`name`, `population`, `country`, `continent`)
VALUES ('Southern California', 23800000, 'United States', 'North America');
--population figure sourced from:
--https://en.wikipedia.org/wiki/Southern_California
|
ALTER TABLE ONLY schools
ADD COLUMN type text;
--;;
UPDATE schools SET type = 'global';
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.