将SQL Select *语句转换为delete语句

时间:2014-03-06 04:50:37

标签: mysql

我有一个SQL语句,它从我的数据库中提取符合条件的记录。

SELECT * FROM `t_questions` LEFT JOIN `t_syllabus` ON `t_syllabus`.`syllabus_id` =    `t_questions`.`question_syl_reference_id` WHERE `t_syllabus`.`syllabus_training_block` = 'CPL';

这可以正常工作并返回我想要的所有内容。

我现在需要写一个状态来删除使用相同条件的问题。

到目前为止,我已经尝试了这个但是我收到了错误。

DELETE FROM t_questions WHERE question_id IN(SELECT * FROM `t_questions` LEFT JOIN `t_syllabus` ON `t_syllabus`.`syllabus_id` = `t_questions`.`question_syl_reference_id` WHERE `t_syllabus`.`syllabus_training_block` = 'CPL')

我手边没有错误消息,但稍后会更新。

为什么这不起作用的任何想法?

感谢。

2 个答案:

答案 0 :(得分:3)

试试这个

DELETE FROM t_questions 
WHERE question_id IN
              (SELECT question_id  
               FROM `t_questions`.`t_questions` LEFT JOIN `t_syllabus` ON `t_syllabus`.`syllabus_id` = `t_questions`.`question_syl_reference_id`
               WHERE `t_syllabus`.`syllabus_training_block` = 'CPL')

答案 1 :(得分:1)

正如其他人所说,您在子选择中选择了多个值。

你可能有兴趣在这里做一个存在。存在查询通常更好地优化,因此比在。

中更快

看起来像这样:

DELETE FROM t_questions as t_outer
WHERE exists
              (SELECT 1
               FROM `t_questions`.`t_questions` as t_inner 
               LEFT JOIN `t_syllabus` ON `t_syllabus`.`syllabus_id` = `t_questions`.`question_syl_reference_id`
               WHERE `t_syllabus`.`syllabus_training_block` = 'CPL'
               AND t_inner.question_id = t_outer.question_id)