【问题标题】:SQL - How to put beside two records of the same table in the same rowSQL - 如何将同一表的两条记录放在同一行中
【发布时间】:2015-06-09 14:23:44
【问题描述】:

我有一个这样结构的表:

+------------+-----------------+----------+
| xreference |      title      | language |
+------------+-----------------+----------+

我希望它通过 SQL 查询获得类似的东西:

+------------+---------------+-----------------+--------------+--------------+
| xreference |   title_eng   |    title_ita    | language_eng | language_ita |
+------------+---------------+-----------------+--------------+--------------+

我怎样才能得到这个结构?有没有一种方法可以在同一行中组织同一张表的两条记录?

例如,如果我有这个数据:

+------------+-----------------+----------+
| xreference |      title      | language |
+------------+-----------------+----------+
|          1 | example_title   | eng      |
|          1 | example_title_2 | ita      |
+------------+-----------------+----------+

我想得到这样的东西:

+------------+---------------+-----------------+--------------+--------------+
| xreference |   title_eng   |    title_ita    | language_eng | language_ita |
+------------+---------------+-----------------+--------------+--------------+
|          1 | example_title | example_title_2 | eng          | ita          |
+------------+---------------+-----------------+--------------+--------------+

【问题讨论】:

标签: mysql sql datatable


【解决方案1】:

在您的情况下,最简单的方法可能是条件聚合:

select xreference,
       max(case when language = 'eng' then title end) as title_eng,
       max(case when language = 'ita' then title end) as title_ita,
       'eng' as language_eng, 'ita' as language_ita
from thisdata t
group by xreference;

我不确定最后两列应该做什么。

与使用join 相比,此方法的优势是双重的。首先,添加新语言很容易。而且,这将显示所有 xreference 值,即使是那些没有英语和/或意大利语翻译的值。

【讨论】:

  • 我希望存储在我的表中的所有值不仅是最大值(或最小值或计数)。没有这些运算符是否可以执行这种条件聚合?
  • @madmad,这将为您提供最多一个值,即唯一值!
  • @madmad 。 . .这假设每个xreference 最多有一个英文标题和一个意大利标题。如果不是这样,您可能需要group_concat()
【解决方案2】:

进行自联接但没有子选择:

SELECT t1.title as title_eng, t2.title as title_ita
from table1 t1
join table2 t2 on (t2.xreference = t1.xreference)
where t1.language = 'eng' and t2.language = 'ita'

【讨论】:

  • 只是一个评论,这只会返回具有英语和意大利语两种语言的 xreference。如果缺少一种语言,则不会返回任何内容。
  • 当然。他可以根据自己想要获得的内容使用外连接。
  • 可惜 MySQL 没有完整的外部连接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多