【问题标题】:Inner join one to many unique_id between two table两个表之间的内连接一对多 unique_id
【发布时间】:2021-11-29 03:37:03
【问题描述】:

一个表 t1 有一个唯一的 id u1

另一个表t2有3个unique_id u2a, u2b, u2c

如何在两个表之间进行内连接,以便 表 t1 的 u1 连接表 t2 的 u2a、u2b 或 u2c。

【问题讨论】:

  • 只标记您使用的数据库。
  • 听起来是数据库设计错误正在给您带来一些问题
  • 为什么结果中没有“ram usa”和“mohan usa”?如果您只需要包含一个名称,请添加在多个匹配项时仅包含一个的规则。另外,为什么不包括“chirs india”?
  • @DanGuzman 感谢您的回复。抱歉,我更改了输出表

标签: mysql sql postgresql


【解决方案1】:

我认为这不是最佳做法,但请尝试:

select t1.name,t2.country
      from table1 t1 
      inner join table2 t2
      on t1.u1=t2.u2a
union 
select t1.name,t2.country
     from table1 t1 
     inner join table2 t2
     on t1.u1=t2.u2b
union 
select t1.name,t2.country
       from table1 t1 
       inner join table2 t2
       on t1.u1=t2.u2c;

演示:https://www.db-fiddle.com/f/7yUJcuMJPncBBnrExKbzYz/116

如果您想按顺序命名,可以在查询末尾添加order by name desc;

select t1.name,t2.country
      from table1 t1 
      inner join table2 t2
      on t1.u1=t2.u2a
union 
select t1.name,t2.country
     from table1 t1 
     inner join table2 t2
     on t1.u1=t2.u2b
union 
select t1.name,t2.country
       from table1 t1 
       inner join table2 t2
       on t1.u1=t2.u2c
order by name desc;

【讨论】:

  • 感谢 Ergest 的快速解决方案。我们在 SQL 中是否有任何函数在一行中匹配 1,2 或 3
  • 例如“其中 u1 匹配 u2a、u2b、u2c”。我们可以在这里使用包含或喜欢的功能吗
  • @kundankaushik,您是在问而不使用union?我想不出更好的方法来解决您的问题。
猜你喜欢
  • 2012-04-25
  • 1970-01-01
  • 2019-02-25
  • 2013-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多