左外连接和计数不会列出所有行

时间:2013-05-28 20:58:39

标签: mysql

$select = "select  f.root_id,f.dateTime,f.name,count(fs.id) as sub_count,CONCAT(u.name,\" \",u.surname) as creator_name_surname".
            " from forum as f ".
            " left outer join users as u on u.id=f.creator_id".
            " left outer join forum as fs on fs.record_root_id=f.root_id"
            ;
    $params = " where fs.status=1 and f.status = 1 and f.record_root_id=$root_id and f.kullanici_firma_id=$kullanici_firma_id";

    $group_by =" GROUP BY f.root_id,f.dateTime,f.name";

此查询未使用count(fs.id)=0列出f中的行。但是我需要列出所有其他行,无论是0还是更大。我的问题是什么?

1 个答案:

答案 0 :(得分:2)

WHERE过滤器fs.status=1的问题。这导致forum fs表上的LEFT JOIN充当INNER JOIN。您应该将该过滤器放在JOIN上。:

select  f.root_id,
    f.dateTime,
    f.name,
    count(fs.id) as sub_count,
    CONCAT(u.name,\" \",u.surname) as creator_name_surname
from forum as f 
left outer join users as u 
    on u.id=f.creator_id
left outer join forum as fs 
    on fs.record_root_id=f.root_id
    and fs.status=1 
where f.status = 1 
    and f.record_root_id=$root_id 
    and f.kullanici_firma_id=$kullanici_firma_id
GROUP BY f.root_id,f.dateTime,f.name