JOIN中的SQL WHERE

时间:2018-02-18 08:36:55

标签: mysql join

我在where子句

中得到了未知列
SELECT `table_1`.*, COUNT(table_2.some_id) AS table2count 
FROM `table_1` 
LEFT JOIN `table_2` ON table_1.id=table_2.some_id 
WHERE (`table2count` > 2)

我也试过

SELECT `table_1`.*, COUNT(table_2.some_id) AS table2count 
FROM `table_1` 
LEFT JOIN `table_2` ON table_1.id=table_2.some_id AND (`table2count` > 2)

2 个答案:

答案 0 :(得分:0)

你可能想要:

SELECT `table_1`.*
FROM `table_1`
WHERE EXISTS (SELECT COUNT(table_2.some_id)
              FROM table_2
              WHERE table_1.id=table_2.some_id 
              HAVING COUNT(table_2.some_id) > 2);

答案 1 :(得分:0)

除非您有派生表,否则不能在where子句中使用别名。在这种情况下,您需要的是having子句。

SELECT `table_1`.some_column, COUNT(table_2.some_id) AS table2count 
FROM `table_1` 
LEFT JOIN `table_2` ON table_1.id=table_2.some_id 
group by `table_1`.some_column, table_2.some_id having table2count > 2

每当您使用group by时,select中的所有列都应属于group by,除了属于sum,{{等聚合函数的一部分1}}等等。