【问题标题】:How can I select rows from one table according to condition in the other table?如何根据另一个表中的条件从一个表中选择行?
【发布时间】:2020-07-28 04:24:05
【问题描述】:

这是我的表格的简化形式。

Match 表有 match_idhost_idaway_id,表 Team > 有 team_idteam_name 列。

我想要的是选择'match_id'、'host team name'、'away team name'。 我使用多个视图来完成此操作,但必须有更优化的东西。

(根据相关的team_id,'主队名称'和'客队名称'将是具有team_name的列)

【问题讨论】:

  • 所以如果我理解正确host_id &away_id 指的是表中的team_id 团队
  • 完全一样

标签: sql sqlite join select where-clause


【解决方案1】:

你需要加入2份teammatch

select m.match_id, 
       t1.team_name host_team_name, 
       t2.team_name away_team_name 
from match m
inner join team t1 on m.host_id = t1.team_id 
inner join team t2 on m.away_id = t2.team_id 

【讨论】:

    【解决方案2】:

    SQL 查询中的列本身可以是 SQL 查询。

    select (select t.team_name from Team t where t.team_id = m.host_id) as home_team
          ,(select t.team_name from Team t where t.team_id = m.away_id) as away_team
      from Match m;
    

    参考这个db<>fiddle

    【讨论】:

    • 酷!感谢分享这个!为了练习,可能会在进一步的查询中尝试。
    • @vortex 对于像您的问题这样的情况,sql 中存在连接。想象一下,如果每一列都由子查询派生,查询会是什么样子。这是糟糕的编码。
    • @forpas 是的,它可能会变得一团糟,但了解其他解决方案总是很酷
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2017-02-11
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 2020-03-04
    • 2014-01-01
    相关资源
    最近更新 更多