我需要构建一个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 | PostID |的用户ID
任何人都可以帮助我努力获取正确的数据到目前为止所有查询都是错误的,我没有发布一个,因为我认为它可能会进一步混淆。
正如我所说,我只需要返回唯一的设备,任何帮助都会非常棒,谢谢
编辑SQLFIDDLE * *
http://sqlfiddle.com/#!2/4217f
答案 0 :(得分: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(评论海报)设备来引用它们
答案 1 :(得分: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 c.cid=@recently_inserted_cid)
union
(select p.uid from posts p where
p.pid = (select c.pid from comments c where c.cid=@recently_inserted_cid))
)
and d.uid in
(select r.uid2 from related r where r.uid1 =
(select c.uid from comments c where c.cid=@recently_inserted_cid))