第一张表:
day | title
1 | "Lorem"
2 | "Ipsum"
第二张表:
day | title
2 | "Amor"
3 | "Zeus"
现在我需要这样的结果:
day | title
1 | "Lorem"
2 | "Amor"
3 | "Zeus"
如何使用单个查询来做到这一点?
编辑:
“宙斯”添加到第二张桌子。
http://sqlfiddle.com/#!2/0dc08/1
SELECT t1.Day, COALESCE(t2.Word, t1.Word) AS Word
FROM Table1 t1
LEFT JOIN Table2 t2 ON t2.Day = t1.Day
UNION ALL
SELECT t2.Day, t2.Word
FROM Table2 t2
LEFT JOIN Table1 t1 ON t1.Day = t2.Day
WHERE t1.Day IS NULL
当在两个表中都找到一天时,上面的代码更喜欢 t2 而不是 t1。底部UNION ALL
的获取所有仅在 t2 中的记录。如果这种情况不能发生,请删除以下UNION ALL
语句。
SELECT t1.day, COALESCE(t2.title, t1.title) title
FROM t1 LEFT JOIN t2 on t1.day = t2.day
在@Glavić 评论之后,这里应该考虑一个t2
没有数据的解决方案:t1
SELECT t1.day, COALESCE(t2.title, t1.title) title
FROM t1 LEFT JOIN t2 on t1.day = t2.day
UNION ALL
SELECT t2.day, t2.title
FROM t2 LEFT JOIN t1 on t2.day = t1.day
WHERE t1.day IS NULL
除了 Eli Gassert 的解决方案,避免两次加入两个表(并且也在每个 DBMS 上运行)
SELECT day,
COALESCE(MAX(CASE WHEN x = 2 THEN title END),
MAX(CASE WHEN x = 1 THEN title END))
FROM (
SELECT day, title, 1 AS x FROM t1
UNION ALL
SELECT day, title, 2 AS x FROM t2
) AS tX
GROUP BY day;
如果 MySQL 支持 FULL join 它会容易得多:
SELECT
COALESCE(t1.day, t2.day),
COALESCE(t2.titl, t1.titl)
FROM t1 FULL JOIN t2 ON t1.day = t2.day;
SELECT *
FROM (
SELECT * FROM t2
UNION
SELECT * FROM t1
) AS tX
GROUP BY day
在sqlfiddle上进行测试。
这是另一种方式 -
select a.day, case when a.title <> b.title then b.title else a.title end title
from table1 a
left join table2 b
on a.day = b.day
使用 GROUP BY day 应该可以解决问题。