MYSQL trying to get other attributes from max value - mysql

I have this trigger
DELIMITER $$
CREATE TRIGGER before_bid_insert
BEFORE INSERT ON Bids
FOR EACH ROW
BEGIN
IF NEW.amount > (SELECT B.amount, B.vin FROM Bids B WHERE B.vin = NEW.vin AND B.amount = (SELECT MAX(amount) from Bids)) THEN
INSERT INTO Notifications (buyer, outbidded, vin, amount) values (NEW.buyer, B.buyer, NEW.vin, NEW.amount);
END IF ;
END$$
DELIMITER ;
With tables
CREATE TABLE Auctions
(seller VARCHAR(100),
vin VARCHAR(20),
brand VARCHAR(20),
cartype VARCHAR(20),
model VARCHAR(20),
color VARCHAR(20),
minprice int,
dt DATETIME,
PRIMARY KEY (vin, seller)
);
CREATE TABLE Bids
(buyer VARCHAR(20),
vin VARCHAR(20),
amount int,
autobid int,
upperlimit int,
PRIMARY KEY(buyer, vin, amount),
FOREIGN KEY (vin) REFERENCES Auctions(vin)
);
CREATE TABLE Notifications
(buyer VARCHAR(20),
outbidded VARCHAR(20),
vin VARCHAR(20),
amount int,
PRIMARY KEY(vin, buyer),
FOREIGN KEY (vin) REFERENCES Bids(vin),
FOREIGN KEY (buyer) REFERENCES Bids(buyer)
);
However whenever I run it, it says operand should contain 1 columns.
What i'm trying to do is, if the row thats being inserted has a higher amount value than any row already in the bids table with the same VIN as the new row, then insert the values into notifications.

You can do this to help with both your issues:
SELECT B.amount INTO #amount, B.buyer INTO #buyer
FROM Bids B WHERE B.vin = NEW.vin AND B.amount = (SELECT MAX(amount) from Bids)
IF NEW.amount > #amount THEN
INSERT INTO Notifications (buyer, outbidded, vin, amount)
values (NEW.buyer, #buyer, NEW.vin, NEW.amount);
Also, not sure but I feel you should have another check in SELECT MAX(amount) from Bids query to include a WHERE clause to check for vin.

Related

I don't know what's wrong with my MYSQL procedure

to try to create a procedure in MYSQL workbench but I'm not succeeding ..
A procedure inserts into a table with parameters coming from an ASP program, inserts into the campaign table, then by the inserted ID, inserts into another table and returns the inserted id from that table in the last table.
What am I doing wrong? I'm getting used to SQL Server....
CREATE PROCEDURE Insert_Campaign_Indicator(
IN Name VARCHAR(50),
IN Email VARCHAR(50),
IN Phone VARCHAR(50),
IN Active INT,
IN Type INT,
IN UserId INT,
IN CampaignId INT
)
BEGIN
INSERT INTO Indicator(Name, Email, Phone, Link, Active, CleaningType, Type, UserId)
VALUES (Name, Email, Phone, uuid(), Active, 2, Type, UserId);
INSERT INTO CampaignIndicator (CampaignId, IndicatorId, Link, ResearchWasSent, ReadyToRefer, AcceptedRefer, Active, UserId)
VALUES (CampaignId, LAST_INSERT_ID(), uuid(),0,0,0, 1, UserId);
SELECT Link FROM CampaignIndicator WHERE Id = LAST_INSERT_ID();
END //
DELIMITER ;
Never use Column names as variable, MySQL gets confused
The code is without DELIMITER because of the dbfddle site you have to add them
CREATE TABLE Indicator(id int AUTO_INCREMENT PRIMARY KEY,Name VARCHAR(50)
, Email VARCHAR(50), Phone VARCHAR(50), Link VARCHAR(36),Active Int, CleaningType int, Type int, UserId int)
CREATE TABLE CampaignIndicator (id int AUTO_INCREMENT PRIMARY KEY,CampaignId int
, IndicatorId int, Link VARCHAR(36), ResearchWasSent int, ReadyToRefer int, AcceptedRefer int
, Active int, UserId int)
CREATE PROCEDURE Insert_Campaign_Indicator(
IN _Name VARCHAR(50),
IN _Email VARCHAR(50),
IN _Phone VARCHAR(50),
IN _Active INT,
IN _Type INT,
IN _UserId INT,
IN _CampaignId INT
)
BEGIN
INSERT INTO Indicator(Name, Email, Phone, Link, Active, CleaningType, Type, UserId)
VALUES (_Name, _Email, _Phone, uuid(), _Active, 2, _Type, _UserId);
INSERT INTO CampaignIndicator (CampaignId, IndicatorId, Link, ResearchWasSent, ReadyToRefer, AcceptedRefer, Active, UserId)
VALUES (_CampaignId, LAST_INSERT_ID(), uuid(),0,0,0, 1, _UserId);
SELECT Link FROM CampaignIndicator WHERE Id = LAST_INSERT_ID();
END
CALL Insert_Campaign_Indicator('A','B','C',1,1,1,1)
| Link |
| :----------------------------------- |
| 28aee8e1-d169-11eb-96e0-00163e64f9cc |
✓
db<>fiddle here

How to get the user with most comments from a 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');

How can I avoid duplicate values in my result set?

CREATE TABLE student
(
s_id int(10) NOT NULL AUTO_INCREMENT,
s_roll_no int(30),
s_name varchar(30),
s_gender varchar(4) not null,
class int(2) not null,
PRIMARY KEY (s_id)
);
CREATE TABLE attendance_date
(
date_today varchar(10),
PRIMARY KEY (date_today)
);
CREATE TABLE attendance_today
(
s_id int(10),
s_roll_no int(30),
s_name varchar(30),
s_gender varchar(4),
class int(2),
date_today varchar(10),
attendance_status varchar(2) not null default 'P'
);
delimiter $$
create trigger after_insertion_into_attendance_date
after insert on attendance_date
for each row
begin
insert into attendance_today(s_id, s_roll_no, s_name, s_gender, class, date_today)
select * from student cross join attendance_date order by date_today, s_id;
end$$
delimiter ;
INSERT INTO student
VALUES
(1,1,'Mridul Kumar','M',1),
(2,2,'Harish Paul','M',1),
(3,3,'Imtiaz Hossain','M',1);
INSERT INTO attendance_date
VALUES
('1st Jan'),
('2nd Jan');
now,
select * from attendance_today;
giving duplicates after every insertion, is there any way to avoid such duplicates inside trigger?
I'm not looking for
select distinct * from attendance_today;
after the trigger gets activated.
This will prevent duplicate values from being inserted
insert into attendance_today(s_id, s_roll_no, s_name, s_gender, class, date_today)
select *
from student cross join attendance_date ad
WHERE NOT EXISTS (
SELECT null FROM attendance_today at
WHERE ad.s_id = at.s_id and ad.date_today = at.date_today
)
order by date_today, s_id;
Try this:
begin
insert into attendance_today(s_id, s_roll_no, s_name, s_gender, class, date_today)
select * from student cross join attendance_date group by s_id order by date_today, s_id;
end$$

MySQL stored procedure to insert or update table

I have two tables:
CREATE TABLE EMPLOYEE (
EMPLOYEE_ID bigint NOT NULL AUTO_INCREMENT,
EMPLOYEE_NO VARCHAR(30),
EMPLOYEE_TYPE VARCHAR(20),
PRIMARY KEY(EMPLOYEE_ID)
);
CREATE TABLE EMP_DETAIL(
EMPLOYEE_ID BIGINT NOT NULL ,
INS_ID VARCHAR(20) ,
SALARY int,
PRIMARY KEY(EMPLOYEE_ID ,INS_ID),
FOREIGN KEY(EMPLOYEE_ID) REFERENCES EMPLOYEE(EMPLOYEE_ID)
);
I want to insert a value in the emp table and the emp_detail table. If the employee already exists, then only insert a record in the emp_details table.
This is the stored procedure:
CREATE PROCEDURE INSERTEMP(
IN EMPLOYEE_NO VARCHAR(30),
IN EMPLOYEE_TYPE VARCHAR(20),
IN INS_ID VARCHAR(20),
IN SALARY INT
)
BEGIN
DECLARE EMPLOYEE_ID BIGINT;
SET #EMPLOYEE_ID= (SELECT IFNULL((SELECT EMPLOYEE_ID FROM EMPLOYEE WHERE EMPLOYEE_NO=EMPLOYEE_NO AND EMPLOYEE_TYPE=EMPLOYEE_TYPE) ,'0'));
IF #EMPLOYEE_ID=0 THEN
INSERT INTO EMPLOYEE (EMPLOYEE_NO ,EMPLOYEE_TYPE ) VALUES (EMPLOYEE_NO,EMPLOYEE_TYPE);
SET #EMPLOYEE_ID=(SELECT LAST_INSERT_ID());
END IF;
INSERT INTO EMP_DETAIL(EMPLOYEE_ID,INS_ID,SALARY) VALUES (#EMPLOYEE_ID,INS_ID,SALARY);
END
If I call the procedure:
CALL INSERTEMP(100, 'PERM','AAA',100);
first execute it created id as 1 in emp table if execute it in second time also insert with new id and third time it fails.
Can someone help?

Read value of a column and assign to another column

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