查询
SELECT DISTINCT walls.wall_id FROM walls
LEFT JOIN wall_categories ON walls.wall_id = wall_categories.wall_id
LEFT JOIN wall_devices ON walls.wall_id = wall_devices.wall_id
WHERE wall_categories.category_id IN (1,2,3)
AND wall_devices.device_id IN (1,2,3)
AND walls.wall_id>113;
上面的查询返回以下结果:
如果我将COUNT添加到完全相同的查询中,如:
SELECT DISTINCT COUNT(walls.wall_id) FROM walls
LEFT JOIN wall_categories ON walls.wall_id = wall_categories.wall_id
LEFT JOIN wall_devices ON walls.wall_id = wall_devices.wall_id
WHERE wall_categories.category_id IN (1,2,3)
AND wall_devices.device_id IN (1,2,3)
AND walls.wall_id>113;
它返回= 14
哪里可以发行?我做错了什么?
答案 0 :(得分:2)
你想:
SELECT COUNT(DISTINCT walls.wall_id)
当你写:
SELECT DISTINCT <expr>, <expr>, <expr>, ...
它有效地将查询视为没有DISTINCT
修饰符,然后从结果集中删除所有重复项。所以当你写道:
SELECT DISTINCT COUNT(walls.wall_id)
它只是对符合查询其余部分条件的所有wall_id
行进行了正常计数。这只返回一个结果,即总行数,然后DISTINCT
删除任何重复,这是微不足道的,因为它只是一个结果。
当您将DISTINCT
修饰符放在COUNT()
中时,它会告诉该函数它应该在计数时删除重复项。
答案 1 :(得分:1)
试试这个:
SELECT COUNT(DISTINCT walls.wall_id) FROM walls
LEFT JOIN wall_categories ON walls.wall_id = wall_categories.wall_id
LEFT JOIN wall_devices ON walls.wall_id = wall_devices.wall_id
WHERE wall_categories.category_id IN (1,2,3)
AND wall_devices.device_id IN (1,2,3)
AND walls.wall_id>113;