我正在尝试使用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
没有运气......任何建议都将不胜感激。
答案 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
子句中。