【问题标题】:SQL join return all rows (in either table or both) on conditionSQL 连接根据条件返回所有行(在任一表中或两者中)
【发布时间】:2016-04-06 09:20:18
【问题描述】:

我有一个表格,其中有一列对内容进行分类:

id  lang   string
1   EN     text1_en
1   DE     text1_de
1   FR     text1_fr
2   EN     text2_en
2   DE     text2_de
3   DE     text3_de
3   FR     text3_fr

我想得到这样的结果:

id  lang  string     id  lang  string    id  lang  string
1   EN    text1_en   1   DE    text1_de  1   FR    text1_fr
2   EN    text2_en   2   DE    text2_de  NULL NULL NULL
NULL NULL NULL       3   DE    text3_de  3   FR    text3_fr

我一开始尝试加入:

select 
  c1.id,c1.lang,c1.string,
  c2.id,c2.lang,c2.string,
  c3.id,c3.lang,c3.string
from 
  mytable c1
  left join mytable c2 on (c1.id=c2.id and c2.lang='DE')
  left join mytable c3 on (c1.id=c3.id and c3.lang='FR')
where
  c1.lang='EN'
order by c1.id

但是我只得到 id 1 和 2 的结果。

如果我将 c1.lang='EN' 移动到 on 条件,我将获得前 3 列的所有表行(不仅是 lang='EN'

【问题讨论】:

  • 我尝试了where c1.lang not in ('DE','FR')where c1.lang is null or c1.lang='EN',但仍然没有获得所需的第三行。

标签: mysql join compare


【解决方案1】:

您可以在 mysql 以外的服务器中使用完全外连接。对于大型表,此查询将需要一些时间。

  select 
      c1.id,c1.lang,c1.string,
      c2.id,c2.lang,c2.string,
      c3.id,c3.lang,c3.string
    from 
      mytable c1 left  join mytable c2 on (c1.id=c2.id and c2.lang='DE')   
      left join mytable c3 on (c1.id=c3.id and c3.lang='FR')  
    where
      c1.lang='EN'

    UNION ALL 

    select 
      c1.id,c1.lang,c1.string,
      c2.id,c2.lang,c2.string,
      c3.id,c3.lang,c3.string
    from 
      mytable c2 left  join mytable c1 on (c2.id=c1.id and c1.lang='EN')   
      left join mytable c3 on (c2.id=c3.id and c3.lang='FR')  
    where
      c2.lang='DE'

    UNION ALL 
    select 
      c1.id,c1.lang,c1.string,
      c2.id,c2.lang,c2.string,
      c3.id,c3.lang,c3.string
    from 
      mytable c3 left  join mytable c1 on (c3.id=c1.id and c1.lang='EN')   
      left join mytable c2 on (c3.id=c2.id and c2.lang='DE')  
    where
      c3.lang='FR'

【讨论】:

  • 谢谢,不过我的数据在 MySQL 上。
  • 那你必须使用 union 或 union all 来模拟全外连接。
  • UNION 而不是UNION ALL 做到了。谢谢!
  • 很高兴它有帮助,关闭您的问题。
  • 我会关闭它,但没有 UI 允许我这样做。我发现的所有主题似乎都不适用于此。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-26
  • 2016-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多