2016-06-30 66 views
0

我有3個表,表頭是我存儲帳戶之間的關係account_has_account1和它的列account_id, account_id1, status其中account_id是帳戶做以下操作account_id1status是一個枚舉類型與價值觀active, inactive其中active指示該帳戶是否實際跟隨,如果該帳戶處於非活動狀態,則帳戶停止跟蹤。SQL:從第3表計算行

第二表被命名爲account_has_photos我將照片存儲一個帳戶存儲在數據庫中,所以它的列account_id, photos_id,所以我需要這個表以獲得從一個帳戶中的另一個帳戶下所有的照片。

但張貼在他們這些有消息,以及這裏是第三臺來自哪個名爲photos_has_message_photos,從這個表我只需要所有發佈的消息的數量在一張照片中,列photos_id, message_photos_id

現在我的查詢是這樣的:

SELECT account_has_photos.photos_id as id, "photos" as type, account_has_photos.update_at, account_has_photos.account_id 
FROM account_has_account1 
    JOIN account_has_photos 
     ON (account_has_photos.account_id = account_has_account1.account_id1 AND account_has_photos.type_id = 17) 
WHERE account_has_account1.account_id = 7 AND account_has_account1.`status` = "Active" 

它表明從哪個帳戶ID 7以下,但在我上獲得的消息總量嘗試都失敗了帳戶的所有照片,我覺得做一個INNER JOIN這樣的:

INNER JOIN (
     SELECT photos_has_message_photos.photos_id, count(photos_has_message_photos.photos_id) as total 
     FROM photos_has_message_photos 
    ) posts 
     ON(posts.photos_id = account_has_photos.photos_id) 

然後我從主posts.total中選擇,但它沒有顯示任何行,甚至沒有顯示任何照片,結果在這一點上是空的,我不知道爲什麼以及如何操作。

完整的查詢是這樣的:

SELECT account_has_photos.photos_id as id, "photos" as type, account_has_photos.update_at, account_has_photos.account_id, posts.total 
FROM account_has_account1 
    JOIN account_has_photos 
     ON (account_has_photos.account_id = account_has_account1.account_id1 AND account_has_photos.type_id = 17) 
    INNER JOIN (
     SELECT photos_has_message_photos.photos_id, count(photos_has_message_photos.photos_id) as total 
     FROM photos_has_message_photos 
    ) posts 
     ON(posts.photos_id = account_has_photos.photos_id) 
WHERE account_has_account1.account_id = 7 AND account_has_account1.`status` = "Active" 

再次,我只需要一個總這兩者在照片信息中發現

+2

每日提示:表格別名! – jarlh

+0

你知道'JOIN'只是'INNER JOIN'的簡寫形式嗎? – jarlh

+0

什麼?!? MySQL如何確定用戶需要什麼樣的加入? – jarlh

回答

1

嘗試此查詢更新內選擇行

SELECT ahp.photos_id as id, "photos" as type, ahp.update_at, ahp.account_id,posts.total 
FROM account_has_account1 
    JOIN account_has_photos 
     ON (ahp.account_id = account_has_account1.account_id1 AND ahp.type_id = 17) INNER JOIN (
     SELECT phmp.photos_id, count(*) as total FROM photos_has_message_photos GROUP BY phmp.photos_id 
    ) posts 
     ON(posts.photos_id = ahp.photos_id) WHERE account_has_account1.account_id = 7 AND account_has_account1.`status` = "Active" 
+0

我現在認識到,如果連接找不到計數函數的數據,會不會中斷?..因爲我一直在做相同的方法其他表,當沒有找到記錄時它們什麼也不顯示,甚至沒有顯示count值的0值 – nosthertus