2

第一张表:

day | title
1   | "Lorem"
2   | "Ipsum"

第二张表:

day | title
2   | "Amor"
3   | "Zeus"

现在我需要这样的结果:

day | title
1   | "Lorem"
2   | "Amor"
3   | "Zeus"

如何使用单个查询来做到这一点?

编辑:

“宙斯”添加到第二张桌子。

4

7 回答 7

2

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语句。

于 2013-09-17T13:32:46.827 回答
1
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
于 2013-09-17T13:25:56.493 回答
0

除了 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;
于 2013-09-17T14:35:40.560 回答
0
SELECT *
FROM (
    SELECT * FROM t2
    UNION
    SELECT * FROM t1
) AS tX
GROUP BY day

sqlfiddle上进行测试。

于 2013-09-17T13:38:46.490 回答
-1

这是另一种方式 -

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
于 2013-09-17T13:41:11.550 回答
-1

使用 GROUP BY day 应该可以解决问题。

于 2013-09-17T13:25:27.047 回答
-1

使用INSERT ON DUPLICATE

例如检查这个答案

那是假设您在 day 列上有 UNIQUE 索引。

于 2013-09-17T13:28:50.027 回答