2012-08-09 30 views
1

我有一個需要建立一個MySQL查詢,以通知用戶一個軟件包時,評論添加到一篇文章。我對這個表是複雜的MySQL查詢相關的用戶和帖子

帖子:PID,UID

評論:CID,UID,PID

用戶:UID

相關: rid,uid1,uid2

設備:的確,UID

一個帖子可以有很多評論,很多評論可以爲每個用戶發佈,並且用戶可以有許多設備。

當插入評論時,我需要爲每個對當前評論做出貢獻的人(包括作者)獲取唯一設備的列表,但僅限於他們與評論用戶相關的位置。

redlated.uid1

持有用戶ID和

related.uid2

保持它們的相關用戶ID例如

----------------------------------- 
| rid  | uid1  | uid2 | 
----------------------------------- 
| 1   | 34  | 43 | 
----------------------------------- 
| 2   | 43  | 34 | 
----------------------------------- 

我已經準備好以下數據

PostAuthorId | 郵政編碼 | 用戶名

誰能幫助我掙扎着爬出來的所有查詢正確的數據,迄今一直是錯的,我還沒有公佈一個,因爲我認爲它甚至可能進一步混淆。

正如我所說的,我需要回到只有唯一的設備,任何幫助將是真棒感謝

編輯SQLFIDDLE * *

http://sqlfiddle.com/#!2/4217f


+0

可否請您添加的所有relavent MySQL表列? – eabraham 2012-08-09 15:43:57

+0

> **帖子**:pid,uid > **評論**:cid,uid,pid > **用戶**:uid > **相關**:rid,uid1,uid2 > **設備**:did,uid devices.did最終是我想要返回 – 2012-08-09 15:50:19

+0

*的每個人都對註釋做出了貢獻*我怎麼知道哪些用途對評論有貢獻?那是在一個單獨的表中? – Nivas 2012-08-09 15:55:11

回答

1

所有你需要的是一個正確的(多)JOIN

SELECT ... 
FROM Posts P 
INNER JOIN Users O ON P.uid = O.uid -- Post owner 
INNER JOIN Devices OD ON O.uid = OD.uid -- Devices of post owner 
INNER JOIN Related R ON O.uid = R.uid1 -- Post owner to other user relationship 
INNER JOIN Comments C ON R.uid2 = C.uid AND P.pid = C.pid -- Comments by related user 
INNER JOIN Devices CD ON C.uid = CD.uid -- Devices of users posting comments 
WHERE pid = yourPostID 

這應該這樣做。
不要忘記,你有設備表兩次,所以你必須通過OD指他們(業主)和CD(評論海報的)設備

+0

這看起來不錯,但它不是返回原來的作者設備@ germann-arlington – 2012-08-09 16:37:49

+0

@Justin Erswell添加另一個JOIN爲 'INNER JOIN設備D1 ON P.uid = D1.uid' – 2012-08-09 16:53:56

+0

不幸的是我得到了同樣的結果遺漏了什麼?你可以更新你的答案,真的很感謝你的時間 – 2012-08-09 16:59:14

0
select distinct d.did from devices d where d.uid in 
(select c.uid from comments c where 
c.pid = (select c.pid from comments c where [email protected]_inserted_cid) 
union 
(select p.uid from posts p where 
p.pid = (select c.pid from comments c where [email protected]_inserted_cid)) 
) 
and d.uid in 
(select r.uid2 from related r where r.uid1 = 
(select c.uid from comments c where  [email protected]_inserted_cid))