在过去的几天里,我一直试图让这个复杂的 MYSQL 查询完全正确地工作,当然因为它有很多方面影响它很难确定它是 100% 正常工作的,我对更复杂的 MYSQL 查询一点也不好。我现在的这个查询也很混乱,所以它返回的数据有点分散,我不确定如何解决这个问题。我已经阅读了 MYSQL Join 和所有内容,我有点理解它,但我不确定在我的情况下使用哪个,以及如何正确使用它们。
这是我当前的查询,它应该可以正常工作。(我认为只需要清理,所以我不必有多余的值)
$notificationsq = mysql_query("SELECT
N.*,
N.fromID,
N.date,
N.id AS ID, //I have to do this because if I don't it doesn't return anything,
///I guess because it joins 3 tables with the id column. not sure
///how to call the correct data.
MIN(N.state) AS State,
MAX(N.date) AS newDate,
P.*,
C.*,
P.id AS uniqueID
FROM notifications N
LEFT JOIN comments C ON N.action = 2 AND N.uniqueID = C.id AND C.state=0
LEFT JOIN posts P ON N.action = 1 AND P.id = N.uniqueID
OR N.action = 2 AND P.id = C.postID
WHERE N.userID = '$session'
AND (N.action = 1 AND N.state IN (0, 1) OR N.action = 2)
AND P.state = 0
GROUP BY P.id
ORDER BY
State ASC,
newDate DESC
") or die(mysql_error());
我的表结构:
Table: notifications
id UserID FromID UniqueID Action State Read_Date Date
1 1 2 1 1 0 0 1325993600
2 1 6 2 1 0 0 1325993615
3 1 2 1 2 0 0 1325993622
4 1 6 2 2 0 0 1325993661
5 2 6 2 2 0 0 1325993661
Action = 1 表示 UniqueID 标识 Posts 中的一列;Action = 2 表示 UniqueID 标识 Comments 中的列。
Table: posts
id ToID FromID Post State Date
1 1 2 Hey 0 1325993600
2 1 6 okay yeah 0 1325993615
Table: comments
ID PostID FromID Comment State Date
1 1 2 lol 0 1325993622
2 1 6 ohh 0 1325993661
因此,在 action 为 2 的 Notifications 表中,UniqueID 用于 Comments 表中的“id”。我想要返回的是 PostID,所以在查询中它就像 UniqueID 是这样的:
1
2
1
1
1