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

2019-06-09 20:41发布

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

3条回答
别忘想泡老子
2楼-- · 2019-06-09 20:53

try this:

INSERT IGNORE INTO senders( sender_id, telephone) 
SELECT 1 as sender_id, 0723355888 as telephone 
FROM students WHERE student_id =1
查看更多
对你真心纯属浪费
3楼-- · 2019-06-09 20:54
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
查看更多
放我归山
4楼-- · 2019-06-09 21:14

try using this query -

INSERT IGNORE INTO senders (sender_id, telephone)  
SELECT student_id as sender_id, telephone
FROM students
WHERE student_id=1
查看更多
登录 后发表回答