我设置了基本的消息系统,我使用相同的查询来显示已发送和已接收的消息。它工作得很好,但我需要获得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 | |
+------------------------+--------------+------+-----+---------------------+----------------+
答案 0 :(得分: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
答案 1 :(得分: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;
答案 2 :(得分: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;