0

我有两张桌子:

表:点

|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 |
4

2 回答 2

3

你只需加入 from pointstopairs和 from pairsagain to 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(abbr. ) 组合行。JOIN

于 2013-06-30T10:17:52.237 回答
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  
于 2013-06-30T10:14:52.590 回答