我有两张桌子:
表:点
|key_id | name | x | y |
------------------------
|1 | A |10 |20 |
|2 | A_1 |11 |21 |
|3 | B |30 |40 |
|4 | B_1 |31 |42 |
表:对
|f_key_p1 | f_key_p2 |
----------------------
|1 | 2 |
|3 | 4 |
表'对'定义表'点'中的哪些行应该配对。 如何查询数据库以选择配对行? 我想要的查询结果如下:
|name_1|x_1|x_2|name_2|x_2|y_2|
-------------------------------
|A |10 |20 |A_1 |11 |21 |
|B |30 |40 |B_1 |31 |41 |
答案 0 :(得分:3)
您只需从points
加入pairs
,再从pairs
加入points
。例如。像这样:
SELECT
p1.name AS name_1, p1.x AS x_1, p1.y AS y_1,
p2.name AS name_2, p2.x AS x_2, p2.y AS y_2
FROM points as p1
INNER JOIN pairs ON (p1.key_id = pairs.f_key_p1)
INNER JOIN points AS p2 ON (pairs.f_key_p2 = p2.key_id);
使用INNER JOIN
(缩写JOIN
)只有在两个表中都匹配时才会合并行。
答案 1 :(得分:1)
select p1.name name_1, p1.x x_1, p1.y y_1, p2.name name_2, p2.x x_2, p2.y y_2
from points p1 join pairs p on p1.key_id = p.f_key_p1
join points p2 on p2.key_id = p.f_key_p2