0

我有 4 张桌子

  • 用户
  • 图片
  • 消息
  • 好友请求

我正在尝试在单个查询中获取好友请求和新消息。它运作良好,但当我离开加入“friendsreuqests”时,我得到了多行。

这是我的查询:

SELECT username,
  f1.userid as reqId,
  m1.msg, m1.userid, 
  p1.picHash, p1.extension, UNIX_TIMESTAMP( m1.sent ) AS date
FROM users
  LEFT JOIN pictures p1 ON p1.userid = users.id
  LEFT JOIN messages m1 ON m1.contactid = users.id AND m1.delivered =0
  LEFT JOIN friendrequests f1 ON f1.contactid = users.id AND f1.delivered=0 AND f1.request =1
WHERE users.id =7
ORDER BY date ASC

这是 MySQL 结果:

Kungen  3     gregegerg     1    dc825b1c8a35593be4d172db7    jpg    1369839537
Kungen  12    gregegerg     1    dc825b1c8a35593be4d172db7    jpg    1369839537
Kungen  3     HEJH          1    dc825b1c8a35593be4d172db7    jpg    1369839540
Kungen  12    HEJH          1    dc825b1c8a35593be4d172db7    jpg    1369839540

如您所见,结果翻了一番。我现在只想得到两行。如果我有两条新消息但没有新朋友请求这 2 行应该为 NULL。

4

4 回答 4

2

如果您想在单个查询中获取好友请求消息,那么我希望查询具有union all. 您的查询正在表之间进行连接。这会将有关朋友请求的信息添加为附加。您希望它在其他行中。

我不确定朋友表中的哪些字段对应于您请求的哪些字段。但这里是一个使用查询的例子union all

SELECT username, users.id as reqId, m1.msg, m1.userid, 
       p1.picHash, p1.extension, UNIX_TIMESTAMP( m1.sent ) AS date
FROM users LEFT JOIN
     pictures p1 ON p1.userid = users.id LEFT JOIN
     messages m1 ON m1.contactid = users.id AND m1.delivered =0 
WHERE users.id =7
union all
SELECT username, users.id as reqId, NULL, NULL, 
       NULL, NULL, UNIX_TIMESTAMP( f1.sent ) AS date
FROM users LEFT JOIN
     friendrequests f1
     ON f1.contactid = users.id AND f1.delivered=0 AND f1.request =1
ORDER BY date ASC
于 2013-05-29T15:38:59.783 回答
1

If you LEFT JOIN both friend requests and messages like you do you will get No of messages times number of friend requests in your result set. In you example you have 2 requests and 2 messages resulting in (2*2=) 4 rows.

Perhaps you should consider using a union instead? With a union you will be able to get one row for each friend request and one row for each message. That should suit your needs better. You will still get 4 rows in your example (2+2), though.

于 2013-05-29T15:37:35.407 回答
0

添加GROUP BY包含所有字段的子句肯定会有所帮助,但您必须决定要保留第二个字段的哪个值(3 或 12)。如果您确实知道,该字段总是有 2 行不同,那么您可以同时选择MIN(m1.msg)MAX(m1.msg)

于 2013-05-29T15:36:04.517 回答
0

问题是,如果我是对的,在前两个加入之后你会得到这个:

Kungen  gregegerg       1   dc825b1c8a35593be4d172db7   jpg     1369839537
Kungen  HEJH            1   dc825b1c8a35593be4d172db7   jpg     1369839540

现在加入friendrequests表,f1.contactid = users.id你在两个条目上加入对用户3和12的请求,用户ID1导致:

Kungen  3   gregegerg       1   dc825b1c8a35593be4d172db7   jpg     1369839537
Kungen  12  gregegerg       1   dc825b1c8a35593be4d172db7   jpg     1369839537
Kungen  3   HEJH            1   dc825b1c8a35593be4d172db7   jpg     1369839540
Kungen  12  HEJH            1   dc825b1c8a35593be4d172db7   jpg     1369839540

现在要获得正确的结果,您需要将friendrequests 表加入到与消息或时间戳相关的内容上,因为这是唯一不同的列。

于 2013-05-29T15:42:38.047 回答