mysql query getting last id and insert value if not exist - mysql

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.

Related

insert using Triggers in mysql [duplicate]

I want to make a insert into 2 tables
visits:
visit_id int | card_id int
registration:
registration_id int | type enum('in','out') | timestamp int | visit_id int
I want something like:
INSERT INTO `visits` as v ,`registration` as v
(v.`visit_id`,v.`card_id`,r.`registration_id`, r.`type`, r.`timestamp`, r.`visit_id`)
VALUES (NULL, 12131141,NULL, UNIX_TIMESTAMP(), v.`visit_id`);
I wonder if its possible
It's not possible with one query as INSERT can only insert data to one table in mysql. You can either
write this as two queries and execute them as a batch
create a stored procedure that would execute two insert command
You can wrap those inserts in transaction if you need to make sure that both queries will write the data.
It seems like the problem you are trying to solve is to get the auto-increment value from the "visits" row to insert into "registration". Am I right?
If so, you can just use the LAST_INSERT_ID() function like this:
INSERT INTO `visits` (`visit_id`,`card_id`)
VALUES (NULL, 12131141);
INSERT INTO `registration` (`registration_id`, `type`, `timestamp`, `visit_id`)
VALUES (NULL, 'in', UNIX_TIMESTAMP(), LAST_INSERT_ID());
You can always do something like this
INSERT IGNORE INTO `table2` VALUES ((select id from table1 where col="value"), 3, 4, 5)
INSERT INTO designation as de,
department as da,
profile as pr
(designation_name,
depart_id,
id,
username,
department,
designation)
select de.designation_name,
de.depart_id,da.id,
pr.username,
pr.department,
pr.designation
from
designation,
department,
profile
de.designation_name='project manager' AND de.id='1' OR
de.depart_id='2' AND de.id='2' OR
da.id='2' OR
pr.username='kapil.purohit' AND pr.id='9' AND pr.status='1' OR
pr.department='1' AND pr.id='9' OR
pr.designation='3' AND pr.id='9' AND pr.status='1'
WHERE
de.id = da.id AND
da.id = pr.id AND
de.id = pr.id AND
ORDER BY de.id DESC

Use of NOT EXISTS in SQL queries

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]')

INSERT value using SELECT in mysql

I have 2 tables: users with columns (id,username, password), and user_failed with columns (user_id, failed, time). is there any possible way i can insert into table user_failed by only using username? i try this code but it failed:
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
VALUES (SELECT user_id FROM users WHERE username = 'pokemon','',3)
Your SQL query is incorrect for several reasons.
The following should work if I have interpreted your query correctly.
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
SELECT id, '', 3 FROM users WHERE username = 'pokemon'
INSERTing into a table from a SELECT does not require VALUES ( ... ). Here is an example of how you would use VALUES ( ... ):
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
VALUES (1, '', 3)
Also, your sub query SELECT user_id FROM users WHERE username = 'pokemon','',3 the WHERE clause is invalid. Specifically the '',3 part which I assume is the values you wanted to insert for time and failed.
This will work....you have to add plain parentheses before and after statements.
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`) VALUES ((SELECT user_id FROM users WHERE username = 'pokemon'),'',3)

MySQL if exists insert id else insert into two tables

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)

Mysql insert into 2 tables

I want to make a insert into 2 tables
visits:
visit_id int | card_id int
registration:
registration_id int | type enum('in','out') | timestamp int | visit_id int
I want something like:
INSERT INTO `visits` as v ,`registration` as v
(v.`visit_id`,v.`card_id`,r.`registration_id`, r.`type`, r.`timestamp`, r.`visit_id`)
VALUES (NULL, 12131141,NULL, UNIX_TIMESTAMP(), v.`visit_id`);
I wonder if its possible
It's not possible with one query as INSERT can only insert data to one table in mysql. You can either
write this as two queries and execute them as a batch
create a stored procedure that would execute two insert command
You can wrap those inserts in transaction if you need to make sure that both queries will write the data.
It seems like the problem you are trying to solve is to get the auto-increment value from the "visits" row to insert into "registration". Am I right?
If so, you can just use the LAST_INSERT_ID() function like this:
INSERT INTO `visits` (`visit_id`,`card_id`)
VALUES (NULL, 12131141);
INSERT INTO `registration` (`registration_id`, `type`, `timestamp`, `visit_id`)
VALUES (NULL, 'in', UNIX_TIMESTAMP(), LAST_INSERT_ID());
You can always do something like this
INSERT IGNORE INTO `table2` VALUES ((select id from table1 where col="value"), 3, 4, 5)
INSERT INTO designation as de,
department as da,
profile as pr
(designation_name,
depart_id,
id,
username,
department,
designation)
select de.designation_name,
de.depart_id,da.id,
pr.username,
pr.department,
pr.designation
from
designation,
department,
profile
de.designation_name='project manager' AND de.id='1' OR
de.depart_id='2' AND de.id='2' OR
da.id='2' OR
pr.username='kapil.purohit' AND pr.id='9' AND pr.status='1' OR
pr.department='1' AND pr.id='9' OR
pr.designation='3' AND pr.id='9' AND pr.status='1'
WHERE
de.id = da.id AND
da.id = pr.id AND
de.id = pr.id AND
ORDER BY de.id DESC