MY situation is like this:
I have two tables
TEACHERS and ABSENCES each of them has a column unitid
I want to select the unitid from TEACHERS Table and insert into ABSENCES table.
EDIT:
Can this be added into this query: ("insert into absences (student_id, date) values ('".$_GET['student_id']."','".date('Y-m-d H:i:s')."')");
?
try this
INSERT INTO ABSENCES(unitid) select unitid from TEACHERS
I tried to depict your scenario as below
Create Absence Table
create table absence (absence_id int not null auto_increment primary key,
`date` datetime, `subject` varchar(20),
unit_session varchar(20), unitid int);
Insert Data to Absence Table
insert into absence(`date`, `subject`, unit_session)
values(now(),'Math','first'),(now(),'Biology','second'),(now(),'Physics','third')
Create and insert data to Teachers table
create table teachers (username varchar(10), `password` varchar(10), unitid int);
insert into teachers values('abcdsed','fgdfgfdfgd',23),
('abcdced','fgdfgrtfgd',3),('harikas','fgdfgfdfgd',23);
At this point as you can see, Absence Table don't have any value for unitid column. it's NULL.
Create a temporary table as below
create temporary table temptest(id int not null auto_increment primary key,
unit_id int);
Insert unitid from Teachers to temporary table
insert into temptest(unit_id) select unitid from teachers
Now finally, update Absence table by joining with temporary table like below
UPDATE absence a
JOIN temptest b
ON a.absence_id = b.id
SET a.unitid = b.unit_id
Related
I have the following table:
CREATE TABLE Employees (
EmployeeID INT,
LastName varchar(20) NOT NULL,
FirstName varchar(20) NOT NULL,
Birthdate date
);
I need to write a trigger to record the message "A new row is inserted", and the time of insertion into a new separate table called Employees_audit when inserting a new row into the Employees table.
I am stumped with this and have looked at example triggers to help me but I cannot quite figure out what to do. Any help is very much appreciated.
Reference and here
Consider the following tables:
CREATE TABLE Employees (
EmployeeID INT,
LastName varchar(20) NOT NULL,
FirstName varchar(20) NOT NULL,
Birthdate date
);
create table Employees_audit (
note varchar(255),
inserted_record_dt datetime,
EmployeeID int
);
The trigger you need:
create trigger Insert_Employees_audit after insert on Employees
for each row
begin
insert into Employees_audit (EmployeeID,note, inserted_record_dt) values (new.EmployeeID,'A new row is inserted', now());
end
Some data example
insert into Employees values (1,'Test','Test','2000-01-01');
Result of:
select *
from Employees_audit;
note inserted_record_dt EmployeeID
A new row is inserted 2022-11-21 10:01:34 1
https://dbfiddle.uk/KGa4ditu
I have the following tables in a database:
CREATE TABLE `CRUISE-RES` (
`cruiseid` INT,
`end-day` DATE,
`start-day` DATE
PRIMARY KEY (`cruiseid`));
CREATE TABLE `ROOM` (
`cruise-id` INT,
`price` FLOAT,
FOREIGN KEY (`cruise-id`));
CREATE TABLE `PROFIT` (
`cruiseid` INT,
`total` FLOAT);
With the following sample table inserts:
-- cruise table inserts
insert into `CRUISE-ID` (`cruiseid`,`start-day`,`end-day`)
values (1, '2022/01/01', '2022/01/05'), (1, '2022/01/05', '2022/01/10'), (2, '2022/01/05', '2022/01/10')
-- room table inserts
insert into ROOM (price,`cruise-id`)
values (5,1), (10,1), (25,2)
I also have the following function that shows the profit of each cruiseid based on the number of days in the CRUISE-RES * price per day.
SELECT c.`cruiseid`, sum(rm.`price`*(DATEDIFF(c.`end-date`, c.`start-date`))) AS 'total_profit'
FROM ROOM rm
JOIN `CRUISE-RES` c
ON rm.`cruise-id` = c.cruiseid
GROUP BY rm.`cruise-id`,'cruiseid'
How can I use this information on a trigger that updates the PROFIT table after each insert into CRUISE-RES table?
I am trying to get the user first name with the most comments. How can I do this?
Here are the tables.
The tables below are the setup for the database tables which I am trying to query.
CREATE TABLE User(
userid varchar(3),
firstname varchar(20),
lastname varchar(20),
age int,
PRIMARY KEY(userid)
)ENGINE=INNODB;
CREATE TABLE Comment(
commentid varchar(3),
userid varchar(3),
eventid varchar(3),
title varchar(20),
comment varchar(50),
PRIMARY KEY(commentid),
FOREIGN KEY(userid) REFERENCES AnonymousUser(userid),
FOREIGN KEY(eventid) REFERENCES Event(eventid)
)ENGINE=INNODB;
INSERT INTO User VALUES('U01','Charles','Darwin',99);
INSERT INTO User VALUES('U02','Keisha','Strawn',24);
INSERT INTO User VALUES('U03','Denise','Malcolm',59);
INSERT INTO User VALUES('U04','Dennis','Stewart',19);
INSERT INTO User VALUES('U05','Robert','Johns',45);
INSERT INTO User VALUES('U06','Marsha','Stewart',33);
INSERT INTO Comment VALUES ('C01','A01','E01','Boring Event','This event was boring');
INSERT INTO Comment VALUES ('C02','A02','E01','Nice Nice Event','This event was Nice');
INSERT INTO Comment VALUES ('C03','A03','E03','Wow','This event was Amazing');
INSERT INTO Comment VALUES ('C04','A01','E01','Very Sad','I missed this event');
The query I tried is
SELECT User.userid FROM User
JOIN comment ON comment.userid = user.userid
WHERE (SELECT COUNT(comment)
FROM comment = (SELECT MAX(userid) FROM comment);
SELECT
userid
FROM
comment
GROUP BY userid
ORDER BY count(userid) DESC
LIMIT 1;
Edit: oh, you need the username. Try this:
SELECT firstname
FROM user
WHERE userid = (
SELECT
userid
FROM
comment
GROUP BY userid
ORDER BY count(userid) DESC
LIMIT 1
);
Query to get firstname with most comments is
select a.firstname, max(a.comment_count) from (
select u.firstname, count(c.commentid) comment_count
from user u join comment c on u.userid = c.userid
group by u.firstname
)a;
That said, I noticed
One of the constraints on table 'comment' is pointing to a table 'AnonymousUser' FOREIGN KEY(userid) REFERENCES AnonymousUser(userid). You have not shared the create table statement for that table.
I had to remove this constraint from table definition in order to successfully create this table in my database
CREATE TABLE Comment(
commentid varchar(3),
userid varchar(3),
eventid varchar(3),
title varchar(20),
comment varchar(50),
PRIMARY KEY(commentid)
);
You dataset for table 'comment' has no userid matching 'user.userid' values
I updated the 'comment' table inserts so I could get some result when executing my query.
INSERT INTO Comment VALUES ('C01','U01','E01','Boring Event','This event was boring');
INSERT INTO Comment VALUES ('C02','U01','E01','Nice Nice Event','This event was Nice');
INSERT INTO Comment VALUES ('C03','U03','E03','Wow','This event was Amazing');
INSERT INTO Comment VALUES ('C04','U06','E01','Very Sad','I missed this event');
I am working on MySQL database, and I need to select some data with procedure. So I have something like:
CREATE TABLE pet (id INT, name VARCHAR(20), own_id INT);
insert into pet values (1,"Rufus", 1);
insert into pet values (2,"Bali", 1);
insert into pet values (3,"Lolo", 2);
ref pet.own_id = own.id
CREATE TABLE own (id INT, own_name VARCHAR(20), own_color VARCHAR(20));
insert into own values (1,"Me", "Red");
insert into own values (2,"Other" ,"Green");
And now I wonder how to select / join data to get something like that (as results):
own_name own_color name
Me Red Rufus
Me Red Bali
Other Green Lolo
SELECT own_name, own_color, name
from pet
JOIN own on (pet.own_id = own.id)
;
You have only to join both tables:
Select own_name,own_color, name from own join pet on
pet.own_id = own.id
select o.own_name, o.own_color, p.name from own o, pet p
where p.own_id=o.id
It's a JOIN.
While a JOIN is a valid answer, some people find subqueries easier to read and write:
SELECT own_name, own_color, (SELECT name
FROM pet
WHERE pet.own_id = own.id) AS name
FROM own
This is basically the same as the JOIN method, but then as a subquery
I have a suggestion for your tables: own_id is a foreign key, so instead of
CREATE TABLE pet (id INT, name VARCHAR(20), own_id INT);
CREATE TABLE own (id INT, own_name VARCHAR(20), own_color VARCHAR(20));
I'd do:
CREATE TABLE own (
id INT NOT NULL AUTO_INCREMENT,
own_name VARCHAR(20) NOT NULL,
own_color VARCHAR(20) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE pet (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
own_id INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (own_id) REFERENCES own (id)
);
I added some other things as well.
Improvements/changes:
I assumed none of the fields should be NULL. I added NOT NULL to all the fields making it impossible for a field to have a value of NULL. (If you want some fields to be allowed to have a value of NULL just remove the NOT NULL from the CREATE TABLE statements.)
I made both id fields increment automatically. This means the insert statements can now be just insert into own (own_name, own_color) values ("Me", "Red"); and the database will automatically keep track of the ids for you.
I added primary keys so the database knows that the rows can be identified by the id fields
I added a foreign key constraint, meaning that every own_id in pet must exist in own. If you try to insert or alter a pet row in a way that breaks this constraint mysql will throw an error at you.
I have 6 columns in my table:
Id | Name | Mail id | Gender | Contact Number | father name
while inserting a data into table i wanted to check condition like if Name,mailid,contact number already exists then insert should not happen else record should be inserted.
Can any one suggest how to check the condition while inserting a record.
IF NOT EXISTS (SELECT * FROM Table_Name WHERE Condition you are checking)
BEGIN
INSERT INTO ............. ---<----- Your Insert Statement.....
END
You can define an index on multiple columns, e.g.:
CREATE UNIQUE INDEX arbitrary_index_name ON table_name (Name, mailid, contactnumber);
I also faced similar situation, you can do this by adding unique constraint to your table and using 'insert ignore' statement to add data.
Create table statement:
CREATE TABLE Student (
Id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(50),
Mailid VARCHAR(50),
Gender CHAR,
contactnumber BIGINT,
fathername VARCHAR(50),
UNIQUE(NAME,Mailid,contactnumber));
Insert Ignore statement:
INSERT IGNORE INTO student(NAME, Mailid,Gender,contactnumber,fathername) VALUES('Shekhar', 's#s.com', 'M', 987654321, 'Joshi');