sql—mysql中完全外部连接的计数

6ju8rftf  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(345)

我试图显示完整外部联接表中的总行数。我有下面的代码,但是mysql说有一个重复列的错误。actors和directors这两个表有相同的列,因为它们应该在各自的类别中提供类似的信息。

SELECT COUNT(*) FROM 
(SELECT * FROM directors LEFT OUTER JOIN actors
ON directors.name = actors.name
UNION
SELECT * FROM directors RIGHT OUTER JOIN actors
ON directors.name = actors.name) AS table1;

如何修复代码使其正常运行?仅供参考,括号内的代码运行良好。只有在我输入select count(*)子句时,问题才会出现。

goqiplq2

goqiplq21#

我不知道你想说什么 full join . 但是在mysql中实现它的最好方法是使用两个 left join s和a union :

select count(*)
from ((select name from directors) union -- on purpose
      (select name from actors)
     ) da left join
     directors d
     on da.name = d.name left join
     actors a
     on da.name = a.name;

不过,如果非要我猜的话,您只需要两个表之间不同名称的数目。如果是:

select count(*)
from ((select name from directors) union -- on purpose
      (select name from actors)
     ) da
elcex8rz

elcex8rz2#

最好将正确的连接部分更改为非冗余的,然后只添加单独的计数。
通用版本:

SELECT (SELECT COUNT(*) FROM A LEFT JOIN B ON A.x = B.x) 
+ (SELECT COUNT(*) FROM B LEFT JOIN A ON B.x = A.x WHERE A.x IS NULL)
AS outerJoinSize
;

注意:我将右连接更改为左连接并交换了表;根据我的经验,右连接只会使查询更难阅读(特别是当涉及多个连接时)。
完全不同的选择。。。

SELECT 
( SELECT SUM(dc1.c * IFNULL(ac1.c, 1)) AS jc
  FROM (SELECT name, COUNT(*) AS c FROM directors GROUP BY name) AS dc1 
  LEFT JOIN (SELECT name, COUNT(*) AS c FROM actors GROUP BY name) AS ac1
     ON dc1.name = ac1.name)
+ (SELECT SUM(IF(dc2.name IS NULL, ac2.c, 0)) AS jc
   FROM (SELECT name, COUNT(*) AS c FROM actors GROUP BY name) AS ac2
   LEFT JOIN (SELECT name, COUNT(*) AS c FROM directors GROUP BY name) AS dc2 
      ON ac2.name = dc2.name)

…这一个根据联接字段计算出有多少个匹配项(导演中的3个“bob”示例和演员中的2个“bob”示例表示该名称的6个联接结果)。

jchrr9hc

jchrr9hc3#

因为有两个 name 一列来自 directors 另一张是从 actors table,你呢 select * 这会让db引擎搞不清你想要哪个名字。
如果你只想 count 你可以试试这个的总数。

SELECT COUNT(*) FROM 
(
    SELECT directors.name FROM directors LEFT OUTER JOIN actors
        ON directors.name = actors.name
    UNION
    SELECT directors.name FROM directors RIGHT OUTER JOIN actors
        ON directors.name = actors.name
) table1;

笔记
我建议使用 select 清除列并避免使用 select *

相关问题