我需要构建一个 MySQL 查询,以便在将评论添加到帖子时通知用户软件包。我为此准备的表格是
Posts: pid, uid
Comments: cid, uid, pid
Users: uid
Related: rid, uid1, uid2
Devices: did, uid
一个帖子可以有很多评论,每个用户可以发布很多评论,一个用户可以有很多设备。
插入评论时,我需要为当时对评论做出贡献的每个人(包括作者)获取唯一设备列表,但仅限于与发表评论的用户相关的设备。
redlated.uid1
保存用户ID和
related.uid2
持有他们相关的用户 ID,例如
-----------------------------------
| rid | uid1 | uid2 |
-----------------------------------
| 1 | 34 | 43 |
-----------------------------------
| 2 | 43 | 34 |
-----------------------------------
我有以下数据可用
PostAuthorId | PostID | UserID
任何人都可以帮助我努力获得正确的数据到目前为止所有查询都是错误的,我没有发布一个因为我认为它可能会进一步混淆。
正如我所说,我只需要返回唯一的设备,任何帮助都会很棒,谢谢
编辑 SQLFIDDLE **
http://sqlfiddle.com/#!2/4217f
最佳答案
您只需要一个正确的(多个)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(评论张贴者的)设备引用它们
关于mysql - 相关用户和帖子的复杂 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11886985/