How to make a sql limit - mysql

im making a database system where i want to make a maximum limit on how many seats are avalible. For each movie there should be only 100 seats. What should i do?
create table customer
(p_No int not null,
name varchar (30),
lastname varchar (30),
constraint p_No_pk primary key(p_No))
create table movie
(title varchar (500),
movie_No int not null,
seats int check(seats < 100),
date datetime,
primary key(movie_No))
create table ticket
(ticket_No int identity (1,1) not null,
movie_No int not null,
p_No int not null,
primary key(ticket_No),
foreign key(movie_No)
references movie (movie_No),
foreign key(p_No)
references customer(p_No))

create a check contraint as below.... SQL SERVER
create table movie
(title varchar (500),
movie_No int not null,
seats int ,
date datetime,
primary key(movie_No)
CONSTRAINT CHK_seats
CHECK (seats <100))

Use a CHECK constraint. E.g.:
CREATE TABLE t1 (x TINYINT NOT NULL UNIQUE CHECK (x BETWEEN 1 AND 100));
Or you can create an AFTER INSERT trigger on the table.
create trigger LimitTable
on YourTableToLimit
after insert
as
declare #tableCount int
select #tableCount = Count(*)
from YourTableToLimit
if #tableCount > 100
begin
rollback
end
go

Related

Please, can someone help me to create a trigger in mysql that has a same function with the assertion below?

So basically I want to create a trigger for mysql database that has same/similar function with the assertion code below (since mysql does not support assertion)
Here is the assertion code that I want to replicate using trigger
CREATE ASSERTION assert
CHECK NOT EXISTS(SELECT * FROM paper P WHERE 3 <>(SELECT COUNT(*)
FROM review R
WHERE R.paperid = P.paperid)
);
CREATE ASSERTION atmostfivepapers
CHECK NOT EXISTS(SELECT * FROM pcmember P WHERE 5 <
( SELECT *
FROM review R
WHERE R.email = P.email
)
);
And here is my table
CREATE TABLE paper(
paperid INT UNSIGNED NOT NULL AUTO_INCREMENT,
title VARCHAR(50) NOT NULL,
abstract VARCHAR(250),
pdf VARCHAR(100),
PRIMARY KEY(paperid)
);
CREATE TABLE author(
email VARCHAR(100) NOT NULL,
name VARCHAR(50),
affiliation VARCHAR(100),
PRIMARY KEY(email)
);
CREATE TABLE writePaper(
paperid INT UNSIGNED NOT NULL AUTO_INCREMENT,
email VARCHAR(100),
paper_order INT,
PRIMARY KEY(paperid, email),
FOREIGN KEY(paperid) REFERENCES paper(paperid),
FOREIGN KEY(email) REFERENCES author(email)
);
CREATE TABLE pcmember(
email VARCHAR(100) NOT NULL,
name VARCHAR(20),
PRIMARY KEY(email)
);
CREATE TABLE review(
reportid INT UNSIGNED,
sdate DATE,
comment VARCHAR(250),
recommendation CHAR(1),
paperid INT UNSIGNED,
email VARCHAR(100),
PRIMARY KEY(paperid, email),
FOREIGN KEY(paperid) REFERENCES paper(paperid),
FOREIGN KEY(email) REFERENCES pcmember(email)
);
Thanks in advance
First create another table replicating the columns and their features. Thereafter create a trigger.
CREATE TRIGGER afterInsert_trigger on yourMainTableName
FOR INSERT
AS
INSERT INTO yourTableCopy(column1ofYourReplicateTable, column2OFyourReplicateTable, ... etc)
SELECT column1ofYourMainTable, column2ofYourMainTable, ..., etc
FROM INSERTED
That's what I use in Microsoft SQL server

Use trigger as assertion in MySQL

I have a database and a few tables in MySql. I am trying to implement an Oracle assertion in MySQL using CREATE TRIGGER. I am not sure if I used the proper syntax.
This is what I have so far, but I'm not sure why it's wrong.
CREATE TRIGGER tg_review_before_insert
BEFORE INSERT ON review
FOR EACH ROW
SET NEW.paper = IF((SELECT * FROM paper P WHERE 3 <>(SELECT COUNT(*)
FROM review R
WHERE R.paperid = P.paperid)
);
Here are my tables:
CREATE TABLE paper(
paperid INT UNSIGNED NOT NULL AUTO_INCREMENT,
title VARCHAR(50) NOT NULL,
abstract VARCHAR(250),
pdf VARCHAR(100),
PRIMARY KEY(paperid)
);
CREATE TABLE author(
email VARCHAR(100) NOT NULL,
name VARCHAR(50),
affiliation VARCHAR(100),
PRIMARY KEY(email)
);
CREATE TABLE writePaper(
paperid INT UNSIGNED NOT NULL AUTO_INCREMENT,
email VARCHAR(100),
paper_order INT,
PRIMARY KEY(paperid, email),
FOREIGN KEY(paperid) REFERENCES paper(paperid),
FOREIGN KEY(email) REFERENCES author(email)
);
CREATE TABLE pcmember(
email VARCHAR(100) NOT NULL,
name VARCHAR(20),
PRIMARY KEY(email)
);
CREATE TABLE review(
reportid INT UNSIGNED,
sdate DATE,
comment VARCHAR(250),
recommendation CHAR(1),
paperid INT UNSIGNED,
email VARCHAR(100),
PRIMARY KEY(paperid, email),
FOREIGN KEY(paperid) REFERENCES paper(paperid),
FOREIGN KEY(email) REFERENCES pcmember(email)
);
Here are the assertions I am trying to implement from Oracle SQL code to MySQL SQL code:
CREATE ASSERTION assert
CHECK NOT EXISTS(SELECT * FROM paper P WHERE 3 <>(SELECT COUNT(*)
FROM review R
WHERE R.paperid = P.paperid)
);
CREATE ASSERTION atmostfivepapers
CHECK NOT EXISTS(SELECT * FROM pcmember P WHERE 5 <
( SELECT *
FROM review R
WHERE R.email = P.email
)
);

Error code 30000 sql

I have this
CREATE TABLE TEST_CAR (
CARID CHAR(36) NOT NULL,
DATE_NEW TIMESTAMP,
DATE_EDIT TIMESTAMP,
USER_NEW VARCHAR(63),
USER_EDIT VARCHAR(63),
MANUFACT VARCHAR(50),
MODEL VARCHAR(50),
MILEAGE INTEGER,
PURCHDATE TIMESTAMP,
BATCH VARCHAR(50),
FUELTYPE INTEGER,
PRIMARY KEY (CARDID));
and it still returns
Error code 30000, SQL state 42X93: Table 'TEST_CAR' contains a
constraint definition with column 'CARDID' which is not in the table.
Line 1, column 1
CREATE TABLE TEST_LIST (
LISTID CHAR (36) NOT NULL,
CAR_ID CHAR (36) NOT NULL,
DRIVER_ID CHAR (36) NOT NULL,
DATE_EDIT TIMESTAMP,
DATE_NEW TIMESTAMP,
USER_EDIT VARCHAR (63),
USER_NEW VARCHAR (63),
F_FROM VARCHAR (50),
T_TO VARCHAR (50),
KM INTEGER,
DESCRIPTION VARCHAR (50),
DATE_FROM TIMESTAMP,
DATE_TO TIMESTAMP,
PRIMARY KEY (ID));
CREATE INDEX ON TEST_LIST (CAR_ID ASC);
Error code 30000, SQL state 42X93: Table 'TEST_LIST' contains a
constraint definition with column 'ID' which is not in the table. Line
1, column 1 Error code 30000, SQL state 42X01: Syntax error:
Encountered "ON" at line 1, column 14. Line 17, column 1
You are setting CARDID as primary key, whilst you named your column CARID.
Change
PRIMARY KEY (CARDID));
to
PRIMARY KEY (CARID));
Solution to your second problem
You define ID as primary key even though ID is not in your table

MySQL: "CREATE DATABASE" results in MySQL Error Code: 1064

I recently bought this book called "SQL Queries for Mere Mortals (3rd Edition" to study SQL. It came with MySQL scripts that they said I could run and have example databases to work with and follow along with the book. However, some of the scripts are resulting in an error message. Here is one example script that will not work:
CREATE DATABASE EntertainmentAgencyModify;
USE EntertainmentAgencyModify;
CREATE TABLE Agents (
AgentID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
AgtFirstName nvarchar (25) NULL ,
AgtLastName nvarchar (25) NULL ,
AgtStreetAddress nvarchar (50) NULL ,
AgtCity nvarchar (30) NULL ,
AgtState nvarchar (2) NULL ,
AgtZipCode nvarchar (10) NULL ,
AgtPhoneNumber nvarchar (15) NULL ,
DateHired date NULL ,
Salary decimal(15, 2) NULL DEFAULT 0 ,
CommissionRate float(24) NULL
);
CREATE TABLE Customers (
CustomerID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
CustFirstName nvarchar (25) NULL ,
CustLastName nvarchar (25) NULL ,
CustStreetAddress nvarchar (50) NULL ,
CustCity nvarchar (30) NULL ,
CustState nvarchar (2) NULL ,
CustZipCode nvarchar (10) NULL ,
CustPhoneNumber nvarchar (15) NULL
);
CREATE TABLE Engagements (
EngagementNumber int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StartDate date NULL ,
EndDate date NULL ,
StartTime time NULL ,
StopTime time NULL ,
ContractPrice decimal(15,2) NULL DEFAULT 0 ,
CustomerID int NULL DEFAULT 0 ,
AgentID int NULL DEFAULT 0 ,
EntertainerID int NULL DEFAULT 0
);
CREATE TABLE Engagements_Archive (
EngagementNumber int NOT NULL ,
StartDate date NULL ,
EndDate date NULL ,
StartTime time NULL ,
StopTime time NULL ,
ContractPrice decimal(15,2) NULL ,
CustomerID int NULL ,
AgentID int NULL ,
EntertainerID int NULL
);
CREATE TABLE Entertainer_Members (
EntertainerID int NOT NULL ,
MemberID int NOT NULL DEFAULT 0 ,
Status smallint NULL DEFAULT 0
);
CREATE TABLE Entertainer_Styles (
EntertainerID int NOT NULL ,
StyleID int NOT NULL DEFAULT 0
);
CREATE TABLE Entertainers (
EntertainerID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
EntStageName nvarchar (50) NULL ,
EntSSN nvarchar (12) NULL ,
EntStreetAddress nvarchar (50) NULL ,
EntCity nvarchar (30) NULL ,
EntState nvarchar (2) NULL ,
EntZipCode nvarchar (10) NULL ,
EntPhoneNumber nvarchar (15) NULL ,
EntWebPage nvarchar (50) NULL ,
EntEMailAddress nvarchar (50) NULL ,
DateEntered date NULL ,
EntPricePerDay decimal(15,2) NULL
);
CREATE TABLE Members (
MemberID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
MbrFirstName nvarchar (25) NULL ,
MbrLastName nvarchar (25) NULL ,
MbrPhoneNumber nvarchar (15) NULL ,
Gender nvarchar (2) NULL
);
CREATE TABLE Musical_Preferences (
CustomerID int NOT NULL DEFAULT 0 ,
StyleID int NOT NULL DEFAULT 0
);
CREATE TABLE Musical_Styles (
StyleID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StyleName nvarchar (75) NULL
);
CREATE INDEX AgtZipCode ON Agents(AgtZipCode);
CREATE INDEX CustZipCode ON Customers(CustZipCode);
CREATE INDEX AgentsEngagements ON Engagements(AgentID);
CREATE INDEX CustomerID ON Engagements(CustomerID);
CREATE INDEX EmployeeID ON Engagements(AgentID);
CREATE INDEX EntertainerID ON Engagements(EntertainerID);
ALTER TABLE Engagements_Archive
ADD CONSTRAINT Engagements_Archive_PK PRIMARY KEY
(
EngagementNumber
);
CREATE INDEX CustomerID ON Engagements_Archive(CustomerID);
CREATE INDEX EmployeeID ON Engagements_Archive(AgentID);
CREATE INDEX EntertainerID ON Engagements_Archive(EntertainerID);
ALTER TABLE Entertainer_Members
ADD CONSTRAINT Entertainer_Members_PK PRIMARY KEY
(
EntertainerID,
MemberID
);
CREATE INDEX EntertainersEntertainer_Members ON Entertainer_Members(EntertainerID);
CREATE INDEX MembersEntertainer_Members ON Entertainer_Members(MemberID);
ALTER TABLE Entertainer_Styles
ADD CONSTRAINT Entertainer_Styles_PK PRIMARY KEY
(
EntertainerID,
StyleID
);
CREATE INDEX EntertainersEntertainer_Styles ON Entertainer_Styles(EntertainerID);
CREATE INDEX Musical_StylesEntertainer_Styles ON Entertainer_Styles(StyleID);
CREATE INDEX EntZipCode ON Entertainers(EntZipCode);
ALTER TABLE Musical_Preferences
ADD CONSTRAINT Musical_Preferences_PK PRIMARY KEY
(
CustomerID,
StyleID
);
CREATE INDEX CustomerID ON Musical_Preferences(CustomerID);
CREATE INDEX StyleID ON Musical_Preferences(StyleID);
ALTER TABLE Engagements
ADD CONSTRAINT Engagements_FK00 FOREIGN KEY
(
AgentID
) REFERENCES Agents (
AgentID
),
ADD CONSTRAINT Engagements_FK01 FOREIGN KEY
(
CustomerID
) REFERENCES Customers (
CustomerID
),
ADD CONSTRAINT Engagements_FK02 FOREIGN KEY
(
EntertainerID
) REFERENCES Entertainers (
EntertainerID
);
ALTER TABLE Entertainer_Members
ADD CONSTRAINT Entertainer_Members_FK00 FOREIGN KEY
(
EntertainerID
) REFERENCES Entertainers (
EntertainerID
),
ADD CONSTRAINT Entertainer_Members_FK01 FOREIGN KEY
(
MemberID
) REFERENCES Members (
MemberID
);
ALTER TABLE Entertainer_Styles
ADD CONSTRAINT Entertainer_Styles_FK00 FOREIGN KEY
(
EntertainerID
) REFERENCES Entertainers (
EntertainerID
) ON DELETE CASCADE,
ADD CONSTRAINT Entertainer_Styles_FK01 FOREIGN KEY
(
StyleID
) REFERENCES Musical_Styles
(
StyleID
);
ALTER TABLE Musical_Preferences
ADD CONSTRAINT Musical_Preferences_FK00 FOREIGN KEY
(
CustomerID
) REFERENCES Customers (
CustomerID
) ON DELETE CASCADE,
ADD CONSTRAINT Musical_Preferences_FK01 FOREIGN KEY
(
StyleID
) REFERENCES Musical_Styles (
StyleID
);
Running this script results in the following error message:
16:33:35 CREATE DATABASE EntertainmentAgencyModify Error Code: 1064.
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'CREATE DATABASE EntertainmentAgencyModify' at line 1 0.00041
sec
Screenshot
I have tried running other scripts that came with the book that also starts with "CREATE DATABASE" and some of them ran smoothly without any errors, so I'm confused as to why I'm getting this error message. Any help would be greatly appreciated! Thanks all!
Note that since this script has a "CREATE DATABASE" at the top it will fail if that database already exists. That also means that if it works partially and you run it again, it;ll fail completely the next time. "CREATE DATABASE" is a pretty big hammer, so you probably don't want to get into the habit of doing it a lot. But, having said that, here's an even bigger hammer; add
DROP DATABASE IF EXISTS EntertainmentAgencyModify;
in front of the CREATE and similarly for the others. When you have real data, you, of course, never want to use either of these.
Can you try running the following just by typing it in your mysql console:
CREATE DATABASE EntertainmentAgencyModify;
It should simply work, or at least tell you something more then a syntax error.
The code executes fine. May be its a problem with your MySql.
Try to install a new MySql. :)
https://www.mysql.com/downloads/
Thanks everyone! I have no idea why this works, but I found a solution. I had to simply delete "CREATE " from the first line of the script and re-type it. Then it worked. If anyone has any idea why this seemingly irrelevant solution worked, I'd love to know. Thanks everyone for your help!

Mysql - second auto_increment col with diff behaviour

I have a proposals table like this
- ID (auto_increment)
- proposal_id
- client_id
There a way in sql that the proposal_id increments just for each client_id
example:
ID proposal_id client_id
1 1 1
2 1 2
3 2 1
4 3 1
5 2 2
6 3 2
i know i can get the last poposal_id and +1 and i add the new entry... but i dont want to do a sql instruction just to get this value... instead i want to use in a sql!
Tkz
Roberto
As I understand you wish to have proposal_id as a sequence in a continuos manner per client_id. Either you should normalize the table to split into per-client-table [tricky and not advisable] to do this or write a SELECT
I think this is what you want if using innodb (recommended) although you can simplify this with myisam
delimiter ;
drop table if exists customer;
create table customer(
cust_id int unsigned not null auto_increment primary key,
name varchar(255) unique not null,
next_proposal_id smallint unsigned not null default 0
)engine = innodb;
insert into customer (name) values ('c1'),('c2'),('c3');
drop table if exists proposal;
create table proposal(
cust_id int unsigned not null,
proposal_id smallint unsigned not null,
proposal_date datetime not null,
primary key (cust_id, proposal_id) -- composite clustered primary key
)engine=innodb;
delimiter #
create trigger proposal_before_ins_trig before insert on proposal for each row
begin
declare new_proposal_id smallint unsigned default 0;
select next_proposal_id+1 into new_proposal_id from customer
where cust_id = new.cust_id;
update customer set next_proposal_id = new_proposal_id where cust_id = new.cust_id;
set new.proposal_id = new_proposal_id;
set new.proposal_date = now();
end#
delimiter ;
insert into proposal (cust_id) values (1),(2),(1),(3),(2),(1),(1),(2);
select * from proposal;
select * from customer;
hope it helps :)
i've added the myisam version below for good measure:
drop table if exists customer;
create table customer(
cust_id int unsigned not null auto_increment primary key,
name varchar(255) unique not null
)engine = myisam;
insert into customer (name) values ('c1'),('c2'),('c3');
drop table if exists proposal;
create table proposal(
cust_id int unsigned not null,
proposal_id smallint unsigned not null auto_increment,
proposal_date datetime not null,
primary key (cust_id, proposal_id) -- composite non clustered primary key
)engine=myisam;
insert into proposal (cust_id,proposal_date) values
(1,now()),(2,now()),(1,now()),(3,now()),(2,now()),(1,now()),(1,now()),(2,now());
select * from customer;
select * from proposal order by cust_id;
I think that you could design a complicated enough query to take care of this without any non-sql code, but that's not in the spirit of what you're asking. There is not a way to create the type of field-specific increment that you're asking for as a specification of the table itself.