我在MYSQL
中有一个表格,其中包含以下字段:
issue_id int(11),
label_id int(11)
在此表格中我想根据某个字段的数量删除行数(如果计数为2则删除它,否则不要
DELETE FROM issue_labels
INNER JOIN (
SELECT count(*) c,
`issue_id`
FROM `issue_labels`
GROUP BY `issue_id`
) temp
ON issue_labels.issue_id = temp.issue_id
WHERE c = 2
上面的SQL会引发错误,但是如果我这样做的话:
SELECT *
FROM issue_labels
INNER JOIN (
SELECT count(*) c,
`issue_id`
FROM `issue_labels`
GROUP BY `issue_id`) temp
ON issue_labels.issue_id = temp.issue_id
WHERE c = 2
有效!我想说的是,加入有效但删除命令没有。
我也尝试使用子查询,如:
DELETE FROM issue_labels
WHERE issue_id IN (
SELECT `issue_id`
FROM `issue_labels`
GROUP BY `issue_id`
HAVING count(*) = 2
)
但是这会引发错误,消息是:
"#1093 - 您无法指定目标表' issue_labels'用于FROM子句"
的更新
此外,我更喜欢使用连接而不是嵌套的解决方案,因为我认为连接比子查询更有效。
答案 0 :(得分:0)
试试这个:
DELETE issue_labels
FROM issue_labels
INNER JOIN (
SELECT count(*) c,
`issue_id`
FROM `issue_labels`
GROUP BY `issue_id`
) temp
ON issue_labels.issue_id = temp.issue_id
WHERE c = 2
<强>解释强>
联接强制您使用&#34; DELETE issue_labels FROM issue_labels&#34;而不是正常的&#34; DELETE FROM issue_labels&#34;,因为要删除的表不再是明确的。