自联接其他表上的内连接

时间:2017-05-30 21:51:42

标签: mysql join inner-join self-join

我有一个包含3个表记录,类别和关系的数据库。

records (id, lat, lng)
categories (c_id, c_value)
relational (r_id, c_id)

records
id  | lat      | lng
----------------------
1    23.57258   -35.28412
2    23.54855   -35.18881
3    23.74128   -35.17469

categories
c_id | c_value
---------------
100    groceries
101    bags
102    drinks

relational
id  |  c_id
------------
1     100
1     102
2     101
3     100

relational.r_id = records.id和relational.c_id = categories.c_id 我想从具有不同c_value的记录中获取对,因此我想在记录中进行自联接,并在类别和关系中进行内部联接。 我没有在记录中自我加入

SELECT id, lat, lng, c_value 
FROM records 
JOIN relational 
  ON records.id = relational.id 
JOIN categories 
  ON relational.c_id = categories.c_id 
WHERE c_value = "V1"  

我尝试过类似的东西,但它没有用。我对R1.c_value有疑问。

SELECT R1._id, R1.lat, R1.lng, R1.c_value, R2._id, R2.lat, R2.lng, 
       R2.c_value 
FROM records R1, records R2 
JOIN relational 
  ON records.id = relational.id 
JOIN categories 
  ON relational.c_id = categories.c_id 
WHERE R1.c_value = "groceries" AND R2.c_value = "bags"

你知道我如何组合这3个连接,以便从其他表的标准中取出2行记录? 我希望有这样的输出: 对于“杂货”和“袋子”作为c.value

1 | 23.57258  |  -35.28412  |  groceries | 2  | 23.54855  |  -35.18881  |  bags    

2 个答案:

答案 0 :(得分:0)

您可以像recordscategories一样自我加入relational表:

SELECT r1.id, r1.lat, r1.lng, r2.id, r2.lat, r2.lng, c.c_value
FROM records r1 JOIN relational rl ON r1.id = rl.r_id
JOIN records r2 ON r2.id = rl.r_id
JOIN categories c ON rl.c_id = c.c_id
WHERE r1.id <> r2.id;

答案 1 :(得分:0)

我终于找到了我想要的东西。我的查询应该是这样的。无论如何,感谢您的帮助和想法。

SELECT r1.id, r1.lat, r1.lng, c1.c_value, r2.id, r2.lat, r2.lng, c2.c_value
FROM records r1 JOIN relational rl1 ON rl1.id = r1.id
JOIN categories c1 ON rl1.c_id = c1.c_id
JOIN records r2 JOIN relational rl2 ON rl2.id = r2.id
JOIN categories c2 ON rl2.c_id = c2.c_id
WHERE  c1.c_value = "groceries" AND c2.c_value = "bags"