How do I combine a SELECT + WHERE query with an IN

2019-06-09 20:26发布

问题:

I want to combine the two following queries, can anyone give me a idea how to do that? (the INSERT query should run only if the SELECT query has a result)

query no 1:

INSERT IGNORE INTO senders(
sender_id,
telephone,
)
VALUES ( 1, 0723355888)

query no 2:

SELECT student_name
FROM students
WHERE student_id =1

回答1:

INSERT INTO senders (sender_id, telephone)
SELECT student_id, student_telephone FROM students
WHERE student_id = 1
LIMIT 1

or if telefone is not a part of the students table, hard code it: This works because if the query 0 rows, no insert is performed at all.

INSERT INTO senders (sender_id, telephone)
SELECT 1, 0723355888 FROM students
WHERE student_id = 1
LIMIT 1


回答2:

try this:

INSERT IGNORE INTO senders( sender_id, telephone) 
SELECT 1 as sender_id, 0723355888 as telephone 
FROM students WHERE student_id =1


回答3:

try using this query -

INSERT IGNORE INTO senders (sender_id, telephone)  
SELECT student_id as sender_id, telephone
FROM students
WHERE student_id=1