如何计入多个表格?

时间:2018-07-05 08:15:25

标签: mysql sql count left-join

我在获取用于另一表行的ID时遇到一些问题。我有三张桌子。一种是类别,文章,视频。在文章和视频中,有一列具有类别ID。这是示例:

表类别:

id | category_name
------------------
1  | News
2  | Sports
3  | Art
4  | Horror

餐桌文章:

id | category_id | title
----------------------------------
1  | 1           | title content 1
2  | 1           | title content 2
3  | 3           | title content 3
4  | 3           | title content 4
5  | 2           | title content 5

桌面视频:

id | category_id | video_title
------------------------------
1  | 1           | video title 1
2  | 2           | video title 2
3  | 3           | video title 3

我想让每个类别ID在其他两个数据库中已经使用了什么时间。像这样:

Category ID 1 is use 3 times
Category ID 2 is use 2 times
Category ID 3 is use 3 times
Category ID 4 is use 0 times

我需要使用什么查询,这样我才能获得所有数据?请任何人知道可以帮助我。预先感谢。

2 个答案:

答案 0 :(得分:1)

首先,您需要将UNION ALL articles表和video表作为子查询,然后使用Outer joinCOUNT函数。

SELECT Concat('Category ID  ', c.id, ' is use ', Count(t.category_id ), ' times') 
FROM   categories c 
       LEFT JOIN (SELECT category_id 
                  FROM   articles 
                  UNION ALL 
                  SELECT category_id 
                  FROM   video) t 
              ON c.id = t.category_id 
GROUP  BY c.id 

SQLFIDDLE:http://sqlfiddle.com/#!9/92cbd0e/12

[结果]

| Concat('Category ID  ', t.id, ' is use ', t.cnt, ' times') |
|------------------------------------------------------------|
|                              Category ID  1 is use 3 times |
|                              Category ID  2 is use 2 times |
|                              Category ID  3 is use 3 times |
|                              Category ID  4 is use 0 times |

注意

  • COUNT函数不计算数字,如果列值遇到null

例如,这是一个示例脚本。

CREATE TABLE T(
   col int
);

INSERT INTO T VALUES (NULL);
INSERT INTO T VALUES (1);

SELECT COUNT(col) FROM  t;  -- RESULT  = 1

SELECT COUNT(*) FROM  t;  --RESULT = 2

示例sqlfiddle:http://sqlfiddle.com/#!9/e2bba7/2

答案 1 :(得分:0)

例如,您可以使用以下查询:

Select category_id, count(1) - 1
  From (
    Select category_id From video
    Union All Select category_id From articles
    Union All Select id From Categories)
  Group By category_id