如何通过选择更多列来插入较小的列?如下所示:
INSERT IGNORE INTO table1 (column1, column2)
SELECT column1, COUNT(*) as total_count, column3
FROM table2
INNER JOIN table3 on table2.id = table3.fk_id
GROUP BY table2.column1
HAVING CASE WHEN column3 = 1 THEN total_count < 10
END
我想只插入2列,但我需要第3列用于HAVING条件。当我从select中删除column3时,它给了我
错误代码:1054未知列&#39;第3列&#39;在&#39;有条款&#39;
答案 0 :(得分:3)
在不查看架构的情况下,我看到的唯一问题是GROUP BY
错过了HAVING
中使用的列,即column 3
。
INSERT IGNORE INTO table1 (column1, column2)
SELECT column1, COUNT(*) as total_count, column3
FROM table2
INNER JOIN table3 on table2.id = table3.fk_id
GROUP BY table2.column1,table2.column3
HAVING CASE WHEN column3 = 1 THEN total_count < 10
END
如果没有包含在GROUP BY
中,则会出现错误
未知列&#39;第3列&#39;在&#39;有条款&#39;
答案 1 :(得分:0)
您可以在Where,Order by,having ....子句中使用任何列,而无需将它们放在SELECT语句中。