如何用INSERT查询合并一个SELECT + WHERE查询?(How do I combine

2019-09-17 11:41发布

我想以下两个查询组合,任何人都可以给我一个想法如何做到这一点? (在INSERT查询应运行只有在SELECT查询是否有结果)

查询无1:

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

查询无2:

SELECT student_name
FROM students
WHERE student_id =1

Answer 1:

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

或者如果telefone不是学生表的一部分,硬编码:这工作,因为如果查询0行,则全部执行没有插件。

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


Answer 2:

尝试这个:

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


Answer 3:

尝试使用此查询 -

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


文章来源: How do I combine a SELECT + WHERE query with an INSERT query?