【问题标题】:Why is my column 'unknown' when using FULL JOIN为什么在使用 FULL JOIN 时我的列“未知”
【发布时间】:2019-06-16 08:23:08
【问题描述】:

我正在学习 sql,并想创建自己的表来练习。我找到了以下网站:https://sqltest.net/

我创建了两个表来练习连接。 LEFT/RIGHT/INNER 连接与我创建的 sql 语句工作正常,但是当我尝试使用 FULL JOIN 时出现以下错误:

Ouuuu snap '':“字段列表”中的未知列“wizards.colours”

这是我做错了什么还是网站出现故障?

CREATE TABLE wizards
(
colours varchar(255),
numbers int,
symbols varchar(255)
);

INSERT INTO wizards
VALUES ('red','49','£'),
       ('blue','83','$'),
       ('blue','72','£'),
('purple','24','%'),
       ('orange','82','$'),
       ('white','67',NULL),
('blue','17','%'),
       ('black','12','%'),
       ('green','97','&'),
('grey','1','%'),
       ('red','6','£'),
       ('red','76','%');

     CREATE TABLE warriors
(
colours varchar(255),
numbers int,
symbols varchar(255)
);  

INSERT INTO warriors
VALUES ('orange','59','£'),
       ('purple','2','£'),
       ('white','11','%'),
('blue','78','%'),
       ('grey','56','$'),
       ('red','5','%'),
('orange','92',NULL),
       ('green','50','$'),
       ('orange','49',NULL),
('red','1','%');

我的sql语句:


SELECT wizards.colours, warriors.numbers, wizards.numbers
FROM wizards
FULL JOIN warriors ON wizards.colours=warriors.colours
ORDER BY wizards.colours;

【问题讨论】:

标签: mysql sql outer-join


【解决方案1】:

MySQL 不支持full join:

你可以使用left + union + right join:

select * from (
    SELECT wizards.colours, warriors.numbers as warriors_numbers, wizards.numbers as wizards_numbers
    FROM wizards  
    LEFT JOIN warriors  ON wizards.colours=warriors.colours

    UNION

    SELECT wizards.colours, warriors.numbers as warriors_numbers, wizards.numbers as wizards_numbers
    FROM wizards  
    RIGHT JOIN warriors  ON wizards.colours=warriors.colours
) T
ORDER BY colours;

Online demo at db<>fiddle

【讨论】:

    【解决方案2】:

    MySQL 不支持FULL JOIN。但是,LEFT JOIN/RIGHT JOIN hack 并不是实现它的最佳方式。例如,它不能正确处理重复。

    更好的方法是:

    select cc.colours,
           wa.numbers, wi.numbers   -- whatever you want here
    from ((select wi.colours 
           from wizards
          ) union  -- on purpose to remove duplicates
          (select wa.colours
           from warriors wa
          )
         ) c left join
         wizards wi
         on wi.colours = c.colours left join
         warriors wa
         on wa.colours = c.colours;
    

    即使这也不是 100% 等效的,因为它不能正确处理 NULL 值。但是,它通常会得到正确的意图。您可以通过更改ON 条件以使用NULL-安全比较on (wi.colours &lt;=&gt; c.colours&gt; 来修复NULL 处理。

    更重要的是,您不需要FULL JOIN。在格式正确的数据库中几乎不需要它们。

    在这种情况下,这意味着您有一个具有正确格式的外键约束的colours 表。这是实体关系建模的一部分,也是实现此类关系的正确方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-25
      • 1970-01-01
      • 2011-03-14
      • 2020-03-07
      • 1970-01-01
      相关资源
      最近更新 更多