这是我目前的数据库结构:
// users
+----+--------+
| id | name |
+----+--------+
| 1 | Jack |
| 2 | Peter |
| 3 | John |
| 4 | Barman |
| 5 | Ali |
+----+--------+
// vote
+----------+---------------+
| voter_id | owner_post_id |
+----------+---------------+
| 2 | 3 |
| 4 | 2 |
| 1 | 1 | -- people can vote to its own posts
| 5 | 2 |
| 2 | 2 |
| 3 | 2 |
+----------+---------------+
这是预期的输出:(对于用户2
)
+---------+-----------+----------+------------+
| user_id | user_name | voter_id | voter_name |
+---------+-----------+----------+------------+
| 2 | Peter | 4 | Barman |
| 2 | Peter | 5 | Ali |
| 2 | Peter | 3 | John |
+---------+-----------+----------+------------+
注意:通常结果中应该还有一行,如下所示:
| 2 | Peter | 2 | Peter |
但我不想得到user_id
和voter_id
相同的那些。我怎么能这样做?
我当前的查询:
SELECT u.id, u.name, v.voter_id
FROM users u
INNER JOIN vote v
ON u.id = v.owner_post_id
WHERE u.id = 2 -- for user 2
答案 0 :(得分:1)
你需要加入users
表两次,一次为投票关系的每一方。
SELECT t2.id AS user_id,
t2.name AS user_name,
t3.id AS voter_id,
t3.name AS voter_name
FROM vote t1
INNER JOIN users t2
ON t1.owner_post_id = t2.id
INNER JOIN users t3
ON t1.voter_id = t3.id
WHERE t1.owner_post_id = 2 AND
t1.voter_id <> t1.owner_post_id