我有一个具有这种结构的表:
+------------+-----------------+----------+
| 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 |
+------------+---------------+-----------------+--------------+--------------+
答案 0 :(得分:2)
您案例中最简单的方法可能是条件聚合:
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
值,即使那些没有英语和/或意大利语翻译的值。
答案 1 :(得分:0)
进行自我加入但没有子选择:
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'