SQL查询。如何合并这两个表?

时间:2019-12-03 04:16:10

标签: mysql sql join

我有两个表:

Table A 
|user_id| |type     |revenues|
101,       comic,    10
101,       adventure,30
101,       comic,    10
102,       romantic, 20

Table B

|type    |
comic
adventure
romantic
animate

其中表B包含整个书籍类型。表A包含交易。如何将两个表合并为一个新表,以便显示每个人的交易。 (注意:1,对于一个人没有购买的book_types,收入应为零。2,同一user_id和类型组合的总和(收入))。例如,新表应类似于:

Table New
101, comic,     20
101, adventure, 30
101, romantic,  0
101, animate,   0
102, comic,     0
102, adventure, 0
102, romantic,  20
102, animate,   0

要创建表,可以使用以下代码:

create table A(usr_id integer, book_type varchar(100), revenues integer);
create table B(book_type varchar(100));
insert into A(usr_id, book_type, revenues) values(101, "comic", 10);
insert into A(usr_id, book_type, revenues) values(101, "comic", 10);
insert into A(usr_id, book_type, revenues) values(101, "adventure",30); 
insert into A(usr_id, book_type, revenues) values(102, "romantic",20); 

insert into B(book_type) values("comic");
insert into B(book_type) values("adventure");
insert into B(book_type) values("romantic");
insert into B(book_type) values("animate");

如果只有一种user_id,我可以提出一个解决方案(请参阅下文)。但是我不知道如何处理有很多user_id的情况。

select case when tmp.user_id is NUll then 101 else tmp.usr_id END,  
B.book_type, case when tmp.revenues is NULL then 0 else tmp.revenues 
END
from 
(
select usr_id, book_type, sum(revenues) as revenues
from A
group by usr_id, book_type
) tmp 
right join B on tmp.book_type = B.book_type

2 个答案:

答案 0 :(得分:1)

您可以使用CROSS和LEFT连接的组合,如下所示,以获取所需的输出。

DEMO HERE

SELECT A.user_id,B.type,
CASE WHEN ISNULL(C.revenues) = 1 THEN 0 ELSE C.revenues END
FROM (
    SELECT DISTINCT user_id 
    FROM Table_A) A
CROSS JOIN Table_B B
LEFT JOIN Table_A C ON A.user_id = C.user_id AND B.type = C.type
ORDER BY A.user_id,B.type

答案 1 :(得分:1)

类似于上一个答案,但是包括给定的user_idtype组合的收入总和:

SELECT q1.user_id, q1.type, IFNULL(SUM(revenues),0) 
FROM
    (
     SELECT DISTINCT user_id, TableB.type
     FROM TableA CROSS JOIN TableB
     ) q1 
LEFT JOIN TableA ON q1.user_id = TableA.user_id AND q1.type = TableA.type
GROUP BY q1.user_id, q1.type
ORDER BY q1.user_id;

方法是:

  1. 交叉连接两个表以生成所有可能的user_id和类型配对

  2. 在新的交叉联接临时表和表A的收入之间进行联接

  3. 将user_id和类型组合的收入相加,如果为null,则为0

SQLFiddle here