MySQL中完全外部联接的计数

时间:2018-09-07 18:52:31

标签: mysql sql union

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

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(*)子句时,问题才会出现。

3 个答案:

答案 0 :(得分:1)

因为有两列name列,其中一列来自directors表,另一列来自actors表,而您select *会让数据库引擎混淆您使用的名称想得到。

如果您只想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 *

答案 1 :(得分:0)

最好更改非冗余的正确连接部分,然后单独添加 计数。

通用版本:

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
;

注意:我将RIGHT JOIN更改为LEFT JOIN并交换了表;根据我的经验,RIGHT JOIN只会使查询更难阅读(尤其是涉及多个联接时)。


一个完全不同的选择...

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个“鲍勃”实例和演员中2个实例意味着该名称的6个联接结果)。

答案 2 :(得分:0)

我不确定您对full join的看法。但是在MySQL中实现它的最佳方法是使用两个left join和一个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