在WHERE子句中使用Count值

时间:2014-01-31 22:55:50

标签: mysql sql

我正在尝试使用COUNT的结果来限制结果。例如,我只想显示count(matching_img_count)大于/等于2的行。

SELECT tel_number.number, COUNT(DISTINCT(i2.id_img)) as matching_img_count
    FROM img_reference i
        JOIN img_reference i2 ON i.id_img = i2.id_img
            AND i2.id_tel=13777
        JOIN tel_number ON i.id_tel = tel_number.id_tel
WHERE tel_number.id_tel != 13777
GROUP BY i.id_tel, i2.id_tel

我尝试了两件事:

HAVING matching_img_count >= 2

WHERE matching_img_count >= 2

没有运气......任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT tel_number.number, COUNT(DISTINCT(i2.id_img)) as matching_img_count
    FROM img_reference i
        JOIN img_reference i2
             ON i.id_img = i2.id_img
        JOIN tel_number
             ON i.id_tel = tel_number.id_tel
WHERE tel_number.id_tel != 13777
       AND i2.id_tel=13777
GROUP BY i.id_tel, i2.id_tel
HAVING COUNT(DISTINCT(i2.id_img)) >= 2

答案 1 :(得分:0)

使用HAVING根据SELECT列表中的值进行过滤:

SELECT tel_number.number, COUNT(DISTINCT(i2.id_img)) as matching_img_count
FROM img_reference i
JOIN img_reference i2 ON i.id_img = i2.id_img
JOIN tel_number ON i.id_tel = tel_number.id_tel
WHERE tel_number.id_tel != 13777
    AND i2.id_tel=13777
GROUP BY i.id_tel, i2.id_tel
HAVING matching_img_count > 1

此外,在执行INNER JOIN时,ON子句应该只具有与两个表相关的条件。所有单表条件都应该在WHERE子句中。