【问题标题】:Don't return repeated ids and give priority to the second table不要返回重复的id,优先返回第二张表
【发布时间】:2023-01-12 23:04:59
【问题描述】:

我有下表:

CREATE TABLE usuarios ( id INT, nome varchar );
INSERT INTO usuarios VALUES
(1, 'Teste'),
(2, 'Teste1'),
(3, 'Teste2'),
(4, 'Teste3'),
(5, 'Teste4'),

CREATE TABLE FichaColab( id INT, nomcompleto varchar );
INSERT INTO FichaColab VALUES
(1, 'Teste Teste'),
(3, 'Teste2 Teste2'),
(5, 'Teste4 Teste4'),

我打算从第一个表中获取所有名称,但如果 id 存在于第二个表中,则返回第二个表的名称而不是第一个表的名称。 这是我想要的结果:

id nome
1 Teste Teste
2 Teste1
3 Teste2 Teste2
4 Teste3
5 Teste4 Teste4

我正在尝试这样:

SELECT usuarios.id, usuarios.nome
FROM usuarios 
UNION 
SELECT FichaColab.Id, nomcompleto
FROM FichaColab

但是这种方式返回两个表中的所有内容并重复 id 而不能。

【问题讨论】:

    标签: mysql


    【解决方案1】:

    这应该做的工作:

    select * from (
    select FichaColab.* from FichaColab left join  usuarios on usuarios.id = FichaColab.id --everithing in table FichaColab 
    union 
    select usuarios.* from FichaColab right join usuarios on usuarios.id = FichaColab.id where FichaColab.id is null --everithing from usuarios where no record in FichaColab exists
    ) as unsorted
    order by ID --sort it
    

    Demo

    【讨论】:

      【解决方案2】:

      您可以在两个表之间使用LEFT JOIN,然后在名称上使用COALESCE,优先考虑全名。

      SELECT u.id, COALESCE(fc.nomcompleto, u.nome) AS nome
      FROM      usuarios   u
      LEFT JOIN FichaColab fc ON u.id = fc.id
      

      查看演示 here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-08
        • 1970-01-01
        • 2019-10-15
        • 1970-01-01
        • 2010-09-16
        • 2018-04-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多