mysql - 连接两个不同列上的表

标签 mysql join

Table 1   Bus_ID   Owner_ID   #owners in Bus
           12345       5558        3
           12345       5856        3
           52858     **7894**      1
           12345       1254        3

Table 2   Owner_1   Owner_2    Relationship
           5558      5856    Parent of Owner_1
           5558      1254    Parent of Owner_1
           1254      5856    Spouse
           5856      1254    Spouse
           **7894**  6868    Spouse
           6868    **7894**  Spouse

我有两个表,我想彼此加入。只能在 Owner_ID = Owner_1Owner_ID = Owner_2 上加入。我想最终获得表 1 中的 Owner_ID

我的预期结果:

Bus_ID  Owner_ID  Owner_1  Owner_2  Relationship 
 12345    5558     5558     5856   Parent of Owner_1
 12345    5558     5558     1254   Parent of Owner_1
 12345    5856     5856     1254   Spouse
 12345    1254     1254     5856   Spouse 

如您所见,如果 Owner_ID 没有出现在表 1 中,我不希望它出现在联合表中,但是当加入 7894 时,因为表 2 中有关系,它会出现无论如何我加入他们的方式。我需要有关连接这两个表的帮助。

select Bus_ID, Owner_ID, Owner_1, Owner_2, Relationship from table 1 
join table 2 on (Owner_ID = Owner_1 AND Owner_ID = Owner_2). 

这个查询不会给出我期望的输出。

最佳答案

尝试在下面使用通过别名连接 table2 的多个实例

select Bus_ID, Owner_ID, t2.Owner_1, t3.Owner_2, t2.Relationship 
from table1 t1 join table2 t2 on t1.Owner_ID = t2.Owner_1 
join table2 t3 on t1.Owner_ID = t3.Owner_2 

关于mysql - 连接两个不同列上的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52990811/

相关文章:

mysql - 这是否足够,或者我是否有竞争条件?

nhibernate queryover join 别名与 where-or 子句

r - 将数据框展开 n 次并添加列编号,重复 1 到 n

php - 数字显示很奇怪,不是小数点后两位

java - 如何使用Servlet批量上传PDF文件并保存到MySQL中?

php - 如何为sphinx查询设置更具体的规则?

r - R中的合并排序连接

MySQL 语句未按预期返回

mysql - 将 3 个表连接到一个表(连接 4 个表)

Mysql左连接: show rows based on another attribute from the joined table