MySQL如何从两个表中选择数据,以便第二个表中的行覆盖第一个表中的数据?

时间:2013-09-17 13:22:41

标签: mysql sql database

第一张表:

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

第二张表:

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

现在我需要这样的结果:

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

如何使用单个查询执行此操作?

修改

“宙斯”加入了第二张桌子。

7 个答案:

答案 0 :(得分: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语句及其下方。

答案 1 :(得分: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

答案 2 :(得分:0)

SELECT *
FROM (
    SELECT * FROM t2
    UNION
    SELECT * FROM t1
) AS tX
GROUP BY day

sqlfiddle上进行测试。

答案 3 :(得分: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;

答案 4 :(得分:-1)

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

答案 5 :(得分:-1)

使用INSERT ON DUPLICATE

检查this answer for example

假设您在日期列上有独特的索引。

答案 6 :(得分:-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