0

在过去的几天里,我一直试图让这个复杂的 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
4

1 回答 1

1

如果您的 state = 0 过滤器限制了与评论的连接,那么帖子上的内部连接可能会过滤掉结果,请尝试将其设为左连接以进行测试。

您的 ORDER BY 子句应该有一个前缀(ORDER BY P.State 或 N.State)。

您遇到 N.id 错误的原因是 id 已被 N.* 选择

您最好使用 ENUM 类型来处理多个状态。这导致具有相同性能的更具可读性的 SQL(即 N.action = 'add',而不是 2)

避免任何选择 *,它容易出错并且性能不如手动选择。

至于清理,我发现使用干净的空格和名称更容易阅读:

SELECT notifications.*
     , notifications.fromID
     , notifications.date
     , MIN(notifications.state) AS State
     , MAX(notifications.date) AS newDate
     , posts.*
     , comments.*
     , posts.id AS uniqueID
FROM notifications
LEFT JOIN comments ON notifications.action = 2
                  AND notifications.uniqueID = C.id
                  AND comments.state = 0
LEFT JOIN posts ON (notifications.action = 1 AND posts.id = notifications.uniqueID)
                OR (notifications.action = 2 AND posts.id = comments.postID)
WHERE notifications.userID = '$session'
  AND (notifications.action = 1 AND notifications.state IN (0, 1) OR notifications.action = 2)
  AND posts.state = 0
GROUP BY posts.id
ORDER BY notifications.State ASC
       , newDate DESC
于 2012-01-10T00:28:34.403 回答