1

我有一个基本的消息系统设置,我使用相同的查询来显示发送和接收的消息。它工作得很好,但我需要为 exp 和 dest 获取 fbook 字段。我想创建两个查询,如果用户发送了他正在查看的消息,则使用一个,如果消息已收到,则使用另一个查询,但也许有更好的方法。

+-----+------+------+----------+----------------+---------------------+------+
| id  | exp  | dest | message  | msg_title      | timestamp           | view |
+-----+------+------+----------+----------------+---------------------+------+
| 114 |  243 |  245 | From 243 | Message to 245 | 2012-04-04 09:26:52 |    0 | 
+-----+------+------+----------+----------------+---------------------+------+

询问

SELECT a.*, b.fbook FROM messages a 
                            JOIN users b ON a.exp=b.id
                            WHERE a.id = 114;

用户表

+------------------------+--------------+------+-----+---------------------+----------------+
| Field                  | Type         | Null | Key | Default             | Extra              |
+------------------------+--------------+------+-----+---------------------+----------------+
| id                     | int(11)      | NO   | PRI | NULL                |  auto_increment | 
| username               | varchar(50)  | NO   |     | NULL                |                  |  
| fbook                  | bigint(64)   | YES  |     | NULL                |                    | 
+------------------------+--------------+------+-----+---------------------+----------------+
4

3 回答 3

2

你想做这样的事情:

SELECT a.*, b.fbook AS `exp-fbook`, c.fbook AS `dest-fbook`
FROM messages a 
JOIN users b ON a.exp=b.id
JOIN users c ON a.dest=c.id
WHERE a.id = 243
于 2012-04-04T06:59:30.743 回答
1

对同一个表使用两个 JOIN。如果使用 LEFT JOIN 比 INNER JOINS 性能更好。

SELECT
    m.*, uexp.fbook, udest.fbook
FROM messages m 
    LEFT JOIN users uexp ON m.exp = uexp.id
    LEFT JOIN users udest ON m.dest = udest.id
WHERE m.id = 243;
于 2012-04-04T06:59:59.190 回答
1

您可以尝试(我认为您想要的 a.id 是 114 而不是 243):

SELECT a.*, ue.fbook AS fbokkExp, ud.fbook AS fbookDest
FROM messages a 
JOIN users ue ON a.exp = ue.id
JOIN users ud ON a.dest = ud.id
WHERE a.id = 114;
于 2012-04-04T07:02:58.260 回答