So I have this table
create table c_order(
order_date date not null,
order_id number,
customer_id number not null,
product_id number not null,
primary key (order_id),
foreign key (customer_id) references Customer(customer_id),
foreign key (product_id) references products(product_id)
);
where customers order for a product.
Now I want it be such that when a data is entered using 'Insert into' then we need not insert the date rather it will be automatically saved to current data. Should I change create table structure for that or use a trigger? What is the syntax then? In trigger is it before/after insert?
https://dev.mysql.com/doc/refman/8.0/en/timestamp-initialization.html
create table c_order(
order_date TIMESTAMP not null DEFAULT CURRENT_TIMESTAMP,
order_id number,
customer_id number not null,
product_id number not null,
primary key (order_id),
foreign key (customer_id) references Customer(customer_id),
foreign key (product_id) references products(product_id)
);
I found my own answer..
Default is not going to work here since the data type is date and functions cannot be used for putting default values in date datatype (for timestamp it can be done).
The answer is trigger. The code is (for oracle.. for mysql sysdate() should be changed to now() )
CREATE or REPLACE TRIGGER auto_insert_date BEFORE INSERT ON c_order
FOR EACH ROW
begin
:NEW.order_date := sysdate();
end;
Related
Please note that this is not my full code for the query. I just need to understand how to compare the time only.
Here is my table creation code
CREATE TABLE IF NOT EXISTS `mydb`.`ActivityBooking` (
`ActivityTime` datetime NOT NULL,
`NumPeople` INT NULL,
`ActivityID` VARCHAR(45) NOT NULL,
`GuideID` VARCHAR(10) NOT NULL,
`Reservation_ReservationID` VARCHAR(10) NOT NULL,
PRIMARY KEY (`ActivityTime`, `ActivityID`),
INDEX `fk_ActivityBooking_Activity1_idx` (`ActivityID` ASC) VISIBLE,
INDEX `fk_ActivityBooking_Staff1_idx` (`GuideID` ASC) VISIBLE,
INDEX `fk_ActivityBooking_Reservation1_idx` (`Reservation_ReservationID` ASC) VISIBLE,
CONSTRAINT `fk_ActivityBooking_Activity1`
FOREIGN KEY (`ActivityID`)
REFERENCES `mydb`.`Activity` (`ActivityID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_ActivityBooking_Staff1`
FOREIGN KEY (`GuideID`)
REFERENCES `mydb`.`Staff` (`StaffID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_ActivityBooking_Reservation1`
FOREIGN KEY (`Reservation_ReservationID`)
REFERENCES `mydb`.`Reservation` (`ReservationID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
Table insertion
Insert into activitybooking values('2020-10-7 15:17:00',6,'C01','S5','R321');
Insert into activitybooking values('2020-12-8 16:15:00',7,'D01','S2','R321');
Insert into activitybooking values('2020-11-9 18:12:00',2,'E01','R321','S4');
Currently I am stuck because I want to display results for bookings made after mid-day and before 4pm. But I don't know how to just compare the time from the datetime format. I am not adding the codes for the other tables in order to keep the information here minimum. But if needed I can provide.
select customerfname, customerlname, activityname
from customer, activitybooking,activity
where activity.activityid = activitybooking.activityid
and activitytime between time('12-0-0') and time('16-0-0');
What you need to do is apply the TIME function to your activitytime column and then compare it to 12:00:00 and 16:00:00:
TIME(activitytime) BETWEEN '12:00:00' AND '16:00:00'
Note if you don't want to include 16:00:00 replace that with 15:59:59. Also, if you write the time strings in HH:mm:ss format then you don't need to apply TIME to them and can just compare directly.
DROP TABLE IF EXISTS CARD_ACCOUNT;
Create Table CARD_ACCOUNT(
acct_no Char(16),
exp_date date,
card_type ENUM('Debit','Credit') NOT NULL,
cust_ID integer NOT NULL
);
DROP TABLE IF EXISTS DEBIT_CARD;
Create Table DEBIT_CARD(
acct_no Char(16),
exp_date date,
bank_no CHAR(9) NOT NULL,
Constraint debit_card_pk primary key(acct_no,exp_date),
Constraint debit_card_fk foreign key(acct_no,exp_date) References card_account(Acct_no,exp_date)
ON UPDATE CASCADE
ON DELETE CASCADE
);
When I try to run this statement I get a "Cannot add foregin key constraint" error in Mysql on the Debit_Card table, why do I get this error the script I am learning from has everything writen the same exact way as I have.
card_account(Acct_no,exp_date) must be Primary Key if you want reference to it in Foreign Key.
and why you don't make it into 1 table?
Create Table CARD_ACCOUNT(
acct_no Char(16),
exp_date date,
bank_no CHAR(9) NOT NULL,
card_type ENUM('Debit','Credit') NOT NULL,
cust_ID integer NOT NULL,
Constraint CARD_ACCOUNT_PK primary key(acct_no,exp_date)
);
i think it serve the same purpose. you already have card_type to know if its debit or credit card so why make separate table for that?
Use the below code, I have just added one primary key constraint in the first table, it will allow you to create the foreign key. But, as "Tim Biegeleisen" commented there is database design problem, you should think again about your database design.
DROP TABLE IF EXISTS CARD_ACCOUNT;
Create Table CARD_ACCOUNT(
acct_no Char(16),
exp_date date,
card_type ENUM('Debit','Credit') NOT NULL,
cust_ID integer NOT NULL,
Constraint debit_card_pk primary key(acct_no,exp_date)
);
DROP TABLE IF EXISTS DEBIT_CARD;
Create Table DEBIT_CARD(
acct_no Char(16),
exp_date date,
bank_no CHAR(9) NOT NULL,
Constraint debit_card_pk primary key(acct_no,exp_date),
Constraint debit_card_fk foreign key(acct_no,exp_date) References card_account(Acct_no,exp_date)
ON UPDATE CASCADE
ON DELETE CASCADE
);
I am working with MySQL I have made a table which have a TIMESTAMP column, which add current time and date to each row added. But I don't know how to initialize it when I insert data to that table. My SQL Queries are :
TABLE
"CREATE TABLE IF NOT EXISTS messages ( mess_id int PRIMARY KEY AUTO_INCREMENT, mess_from int, mess_to int, mess_txt VARCHAR(20000), mess_time TIMESTAMP, FOREIGN KEY (mess_from) REFERENCES users(id),FOREIGN KEY (mess_to) REFERENCES users(id) )"
INSERTION
"INSERT INTO user_messages (NULL,'"+data.from+"','"+data.to+"','"+data.text+"',DEFAULT)"
The problem is, I don't know how to initialize the timestamp column, I tried NULL and DEFAULT but both show me this error of invalid syntax. I want the timestamp field to be initialized automatically! That's it.
On the table creation, set the default on the timestamp column to CURRENT_TIMESTAMP.
CREATE TABLE IF NOT EXISTS messages (
mess_id int PRIMARY KEY AUTO_INCREMENT,
mess_from int,
mess_to int,
mess_txt VARCHAR(20000),
mess_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (mess_from) REFERENCES users(id),FOREIGN KEY (mess_to) REFERENCES users(id) )
EDIT:
For completeness, this will set the mess_time field to the current timestamp when a new record is inserted and does not contain an explicit value for that field. It will have no effect when an UPDATE on that row occurs. You can set it so that on every update the timestamp will be set to the current timestamp using "ON UPDATE CURRENT_TIMESTAMP"
CREATE TABLE IF NOT EXISTS messages (
mess_id int PRIMARY KEY AUTO_INCREMENT,
mess_from int,
mess_to int,
mess_txt VARCHAR(20000),
mess_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (mess_from) REFERENCES users(id),FOREIGN KEY (mess_to) REFERENCES users(id) )
When doing the INSERT, do not specify the timestamp column:
INSERT INTO user_messages (mess_from,mess_to, mess_text) VALUES (#FromValue,#ToValue,#TextValue)
(The above will work in all cases. There is a system variable that controls whether you can use NULL to insert the current_timestamp. This is not standard and less compatible with other SQL engines, so it is often set to standards mode.
The variable is explicit_defaults_for_timestamp, but it has been deprecated, and these non-standard behaviors are set to be removed in future mysql versions, so I would not recommend using it.)
Try the following:
INSERT INTO user_messages (NULL, '"+data.from+"', '"+data.to+"', '"+data.text+"', now());
I'm having issues with setting up a relation between 2 tables called Customer and Customer_Number. I have both tables set to InnoDB both have indexes, but when I go to create the foreign key, I get a "no index defined" error. Below are some screen shots
Here Is the Customer table.
Here is the Customer_Number table.
And here is my error message when trying to create the foreign key.
And lastly, this is the error I get when trying to create the relationship manually.
I just can't seem to figure out the issue, and it's driving me nuts!
the output for SHOW CREATE TABLE Customer is
CREATE TABLE `Customer` (
`Customer_ID` int(11) NOT NULL AUTO_INCREMENT,
`First` varchar(255) NOT NULL,
`Last` varchar(255) NOT NULL,
PRIMARY KEY (`Customer_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
and the output for SHOW CREATE TABLE Customer_Number is
CREATE TABLE `Customer_Number` (
`Num_ID` int(11) NOT NULL AUTO_INCREMENT,
`Customer_ID` int(11) NOT NULL,
`Number` varchar(255) NOT NULL,
PRIMARY KEY (`Num_ID`),
KEY `Customer_ID` (`Customer_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
The two CREATE TABLE statements as posted are correct and should be able to accept a new FOREIGN KEY constraint on Customer_Number.Customer_ID since the necessary criteria are met (same data type as referenced column, comparable index or primary key on referenced column).
An ALTER statement succeeds in my testing:
ALTER TABLE Customer_Number ADD FOREIGN KEY (Customer_ID) REFERENCES Customer (Customer_ID);
Being unfamiliar with how PhpMyAdmin abstracts some RDBMS errors, it is hard to say for sure what exactly has gone wrong in the GUI. But if you run the ALTER statement manually and encounter errors about failed foreign key constraints, that's an indication the referencing table already contains values in the column which do not reference a valid row value in the parent table. To uncover those rows so you can address them, execute a query like:
SELECT * FROM Customer_Number WHERE Customer_ID NOT IN (SELECT Customer_ID FROM Customer)
Once you have found the problematic rows, you can either delete them (if unneeded) or update their values to the value of a valid row value in the referenced table. If the column's definition allowed NULL (which yours does not) you could also UPDATE them to set them NULL then run the ALTER statement again.
It is also possible to disable foreign key checks temporarily, add the constraint, update the rows to match valid parent table values, the reenable foreign key checks.
please try this.
alter table Customer_Number add foreign key(customer_ID) references Customer (Customer_ID);
I am trying to add records into two tables below,
CREATE TABLE customer
(Custno CHAR(3),
Custname VARCHAR(25) NOT NULL,
Custstreet VARCHAR(30) NOT NULL,
Custcity VARCHAR(15) NOT NULL,
Custprov VARCHAR(3) NOT NULL,
Custpcode VARCHAR(6) NOT NULL,
Disc DECIMAL(3,1),
Balance DECIMAL(7,2),
Credlimit DECIMAL(5),
Srepno CHAR(3),
CONSTRAINT pkcustno PRIMARY KEY (Custno),
CONSTRAINT fksrepno FOREIGN KEY (Srepno) REFERENCES salesrep(Srepno)
);
CREATE TABLE orders
(Orderno CHAR(5) UNIQUE NOT NULL,
Orderdate DATE,
Custno CHAR(3) NOT NULL,
CONSTRAINT fkordercust FOREIGN KEY (Custno) REFERENCES customer (Custno)
);
When adding like this,
INSERT INTO orders(Orderno, Orderdate, Custno) VALUES('14587','2011-11-09', '125' );
INSERT INTO orders(Orderno, Orderdate, Custno) VALUES('11547','2011-11-07', '125' );
I get, "Cannot add or update a child row: a foreign key constraint fails (sh.orders, CONSTRAINT fkordercust FOREIGN KEY (Custno) REFERENCES customer (Custno))
"
Is something wrong the table?
You do not have a customer with CustNo = '125'. Because of this, the Foreign key fails. You are trying to place an order for a non-existent customer, the DB throws an error.
Do you actually have a customer row for customer number 125? I think not. The error message is telling you exactly what's wrong.
The foreign key constraint which ensures that no orders can be created for non-existent customers is being violated:
CONSTRAINT fkordercust FOREIGN KEY (Custno) REFERENCES customer (Custno)
Create the customer row first then you can add order rows for that customer to your heart's content.
Your table is fine, you just don't have a customer with a CustNo of '125' in the database.
You have created a foreign key to the customer table, but ( apparently ) inserted no data into it.
Do you have a customer with a number of 125?