2012-03-20 37 views
0

我有一個查詢,通過連接從4個表中選擇數據,我想也計數包含匹配的外鍵的第五個表中的數字行。連接後從表中計數行

這就是我目前的查詢看起來樣子,它不工作

"SELECT 
        ph.pheed_id,ph.user_id,ph.datetime,ph.repheeds, 
        ph.pheed,fav.id,fav.P_id,fav.datetime as stamp, 
        u.username,ava.avatar_small 
        COUNT(pheed_comments.comment_id) as comments 
        FROM favourite_pheeds fav 
        INNER JOIN pheeds ph ON ph.pheed_id=fav.P_id 
        INNER JOIN users u ON u.id=ph.user_id 
        INNER JOIN profiles pr ON pr.user_id=ph.user_id 
        LEFT JOIN user_avatars ava ON ava.avatar_id=pr.avatar 
        ORDER BY stamp DESC 
        LIMIT $offset,$limit"; 

我如何在包含匹配的外鍵第五表計數的行數。

+0

如果您想從第五張表中找到匹配的計數,則使用INNER JOIN。 – Teja 2012-03-20 20:26:14

+0

你的意思是什麼不起作用?你有語法錯誤嗎?或者你的結果是空的? – rekire 2012-03-20 20:26:21

+0

@rekire是的我得到一個語法錯誤 – MrFoh 2012-03-20 20:32:16

回答

1
select ph.pheed_id, 
    ph.user_id, 
    ph.datetime, 
    ph.repheeds, 
    ph.pheed, 
    fav.id, 
    fav.P_id, 
    fav.datetime as stamp, 
    u.username, 
    ava.avatar_small, 
    coalesce(pcc.Count, 0) as comments_count 
from favourite_pheeds fav 
inner join pheeds ph on ph.pheed_id = fav.P_id 
inner join users u on u.id = ph.user_id 
inner join profiles pr on pr.user_id = ph.user_id 
left join user_avatars ava on ava.avatar_id = pr.avatar 
left outer join (
    select pheed_id, count(*) as Count 
    from pheed_comments 
    group by pheed_id --took a guess at the column name here 
) pcc on ph.pheed_id = pcc.pheed_id 
order by stamp desc 
LIMIT $offset, $limit