如何将SELECT + WHERE查询与INSERT查询组合?

时间:2012-05-24 11:22:42

标签: mysql select insert where

我想结合以下两个问题,任何人都可以告诉我如何做到这一点? (INSERT查询只应在SELECT查询有结果的情况下运行)

查询否1

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

查询否2

SELECT student_name
FROM students
WHERE student_id =1

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

尝试使用此查询 -

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

答案 2 :(得分:0)

试试这个:

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