I've made the following SQL statement and it does not work and cannot figure out how to create a functioning one. Here is what i am trying to do.
Check if a value exists in a players table
If the value exists, i want to insert ignore into a roster table
If the value doesnt exist, i want to insert it into the players table and insert it into the roster table
Here is what i have
IF EXISTS (SELECT id AS plyrId FROM players WHERE email = #(:e) LIMIT 1)
BEGIN
INSERT IGNORE INTO roster
(date, teamId, playerId)
VALUES
( (:d), (:t), plyrId )
END
ELSE
BEGIN
INSERT INTO players
(status, date, first_name, last_name, email)
VALUES
( (:s), (:d), (:f), (:l), (:e) )
INSERT IGNORE INTO roster
(date, teamId, playerId)
VALUES
( (:d), (:t), LAST_INSERT_ID() ) //LAST_INSERT_ID() -> I want it to be pulled from the last id inserted from the players table - not sure how to accomplish this
END
Any help is appreciated!
ive tried another attemp without any luck either
IF (SELECT COUNT(*) FROM players WHERE email = (:e) > 0)
INSERT IGNORE INTO roster
(date, teamId, playerId)
(:d), (:t), SELECT id FROM players WHERE email =(:e)
ELSE
BEGIN
.. // havent got to this part yet. it follows the same logic as the one before
END
You must use trigger on event before insert
CREATE TRIGGER test_trigger BEFORE INSERT ON `players table` FOR EACH ROW SET
-- checking value exist or not, for each case write corresponding insert or inserts
This part of the query is highly suspect:
IF EXISTS (SELECT id AS plyrId FROM players WHERE email = #(:e) LIMIT 1)
BEGIN
INSERT IGNORE INTO roster
(date, teamId, playerId)
VALUES
( (:d), (:t), plyrId )
----------------------^
END
Unless you have a variable named plyrId, this will fail. Assigning an alias in a subquery does not define a variable in the outer query.
You can replace it with:
INSERT IGNORE INTO roster(date, teamId, playerId)
SELECT (:d), (:t), id
FROM players
WHERE email = #(:e)
LIMIT 1;
Or, you can change the if to:
IF EXISTS (SELECT plyrdId := id FROM players WHERE email = #(:e) LIMIT 1)
Related
I have read all most of the answers and even tried them. But this is my case where I'm inserting record from a .csv file into the database. I want to insert a record if it does not exist.
Here is my query
INSERT INTO retailer(retailerCode, contact, shopName, address,
retailerType, lastVisit, officeID, createDate)
VALUES ('', '$emapData[1]', '$emapData[2]', '$emapData[3]',
'$emapData[4]', '', '$id', CURDATE())
WHERE NOT EXISTS (SELECT retailerID
FROM retailer
WHERE contact = '$emapData[1]')
Here $emapData is a PHP array that saves the records of the .csv file. The insert statement works fine without this part
WHERE NOT EXISTS (SELECT retailerID
FROM retailer
WHERE contact = '$emapData[1]')
But my goal is not achieved.
You cannot use WHERE with INSERT in that way.
What you can do:
As #Sylwit suggested, create unique index on contact and use INSERT IGNORE
alter table retailer add unique (contact)
Use INSERT INTO SELECT syntax
INSERT INTO retailer(retailerCode,contact,shopName,address,retailerType,lastVisit,officeID,createDate)
select '','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','','$id', CURDATE()
from retailer
WHERE NOT EXISTS (SELECT retailerID FROM retailer WHERE contact='$emapData[1]')
I am struggling to find a solution need assistance in MySQL script:
Here is my solution design:
Insert values in qa_post (which is in database1) table from test1
(database2)
Get max(postid) from database1.qa_posts (which we
just inserted in step # 1) and then
Insert values in qa_postmetas
(which is in database1) but half of the values will come from database2.test1
Here is my script so far:
INSERT INTO database1.qa_posts (type, categoryid, userid, created, title, content, tags)
(SELECT 'Q_QUEUED', '1', '3', NOW(), f.title, f.img, f.tagsv
FROM database2.test1 f)
LIMIT 1;
INSERT INTO database1.qa_postmetas (postid, title, content)
(select MAX(postid) , 'qa_q_extra', f.URL
from database1.qa_posts b
JOIN database2.test1 f on f.id = b.postid)
LIMIT 1 ;
What wrong:
MAX(postid) is coming from database2.test1 instead of database1.qa_posts
I want to add logic that don't insert in database1.qa_posts until I verify f.URL doesn't exist in database2.test1. If it does exist don't do any insert
MAX(postid) --> MAX(b.postid)
Make a UNIQUE index on test1.URL; then the INSERT will fail. Do INSERT IGNORE so that the failure will be silent.
I have two variables
1. inserted_user_id,
2. inserted_address_id
in my MySQL procedure.
I need to use them in insert queries and select queries. Im trying something like
insert into user_new(name, company, email, customer_id) select name,
company, email, inserted_user_id from user_old;
insert into user_address_map(address_id, user_id) select
inserted_user_id,inserted_address_id ;
There two statements are not working. How to use procedure variable's value in the above sql statements?
First make a select to get all the info: (you need to declare these variables first)
SELECT name,
company,
email,
INTO varname, varcompany, varemail
FROM user_old
then use it into insert
INSERT INTO user_new
(name,
company,
email,
customer_id)
VALUES (varname,
varcompany,
varemail,
inserted_user_id);
edit:
First insert the Selected values and get the id of the inserted row
INSERT INTO user_new
(name,
company,
email)
SELECT name,
company,
email
FROM user_old
SET out_param = last_insert_id();
Then update this row with your param
UPDATE user_new
SET customer_id = inserted_user_id
WHERE id = out_param;
I am trying to count total answers, and total correct responses to a given question for students who might be enrolled in multiple classes with a given teacher. I would like the results grouped by test and teacher, with duplicate students removed.
What I would like to get out of the following is:
test1-teacher1-6-4
test1-teacher2-3-2
However, the fact that student3, student4 and student5 are enrolled in different classes with teacher1 (see below) is causing them to be counted twice, so I get...
test1-teacher1-6-6
test1-teacher2-3-2
Here is all the data I am using.
Any thoughts on how to remove the duplicate students? Thanks.
create database test_db;
use test_db;
drop table if exists test;
create table test(test_name varchar (50),student_name varchar(50),result varchar(50));
drop table if exists roster;
create table roster(teacher_name varchar(50),student_name varchar(50), class_name varchar(50));
insert into test values ('test1','student1','c');
insert into test values ('test1','student2','x');
insert into test values ('test1','student3','x');
insert into test values ('test1','student4','c');
insert into test values ('test1','student5','c');
insert into test values ('test1','student6','c');
insert into test values ('test1','student7','c');
insert into test values ('test1','student8','x');
insert into roster values ('teacher1', 'student1', 'class1');
insert into roster values ('teacher1', 'student2', 'class1');
insert into roster values ('teacher1', 'student3', 'class1');
insert into roster values ('teacher1', 'student4', 'class1');
insert into roster values ('teacher1', 'student5', 'class1');
insert into roster values ('teacher1', 'student6', 'class1');
insert into roster values ('teacher1', 'student3', 'class2');
insert into roster values ('teacher1', 'student4', 'class2');
insert into roster values ('teacher1', 'student5', 'class2');
insert into roster values ('teacher2', 'student6', 'class3');
insert into roster values ('teacher2', 'student7', 'class3');
insert into roster values ('teacher2', 'student8', 'class3');
use test_db;
select
test_name,
r.teacher_name,
count(distinct r.student_name) as numTested,
sum(case
when result = 'c' then 1
else null
end) as Q1correct
from
test t
join
roster r ON t.student_name = r.student_name
group by t.test_name , r.teacher_name;
Use a sub-query to remove the duplicates from roster.
select
test_name,
r.teacher_name,
count(distinct r.student_name) as numTested,
sum(case
when result = 'c' then 1
else null
end) as Q1correct
from
test t
join
(select distinct teacher_name, student_name
from roster) r ON t.student_name = r.student_name
group by t.test_name , r.teacher_name;
SQLFIDDLE
I have two tables:table1 and rating
table1(id,name,category)
rating (cid,rating,total_rating,total_rates,photoID)
and now when i insert data into table1 i want to set all data in table rating at zero for that specific photoID from table1, but i dont know how..can someone help me?
You can use LAST_INSERT_ID() to retrieve the ID you just inserted. For example, assuming PhotoID is the relation between table1 and rating:
insert table1 (name,category) values ('waterfall 2', 'nature');
insert rating (rating,total_rating,total_rates,photoID) values
(0, 0, 0, last_insert_id());
I'd rather create a STORED PROCEDURE to make a single call from application. Assuming that you want to INSERT a record on table rating for every insert on table1 and that ID on table1 is set as AUTO_INCREMENT.
DELIMITER $$
CREATE PROCEDURE procedureName
(
IN _name VARCHAR(25),
IN _category VARCHAR(25)
)
BEGIN
INSERT INTO table1 (name, category)
VALUES (_name, _category);
SET #last_ID := LAST_INSERT_ID();
INSERT INTO rating (cid, rating, total_rating, total_rates, photoID)
VALUES (#last_ID, 0,0,0,0);
END $$
DELIMITER ;
and call the procedure,
CALL procedureName('nameHere','categoryHere')
You can use MySql triggers http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html:
CREATE TRIGGER ins_rating AFTER INSERT ON table1
FOR EACH ROW
BEGIN
INSERT INTO rating (cid,rating,total_rating,total_rates,photoID)
VALUES( NEW.ID ,0,0,0,null)
END;
If you want to insert data into TABLE1 and delete it from TABLE2, you can write below listed query:
mysql_query("DELETE * FROM table2");