mysql - SQL 查询。我怎样才能合并这两个表?

标签 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和类型组合,sum(收入))。例如,一个新表应该是这样的:

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

最佳答案

与之前的答案类似,但包括给定 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 和类型组合的收入求和,如果为空则给出 0

SQLFiddle here .

关于mysql - SQL 查询。我怎样才能合并这两个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59150118/

相关文章:

mysql - ./libraries/plugin_interface.lib.php#551 count() : Parameter must be an array or an object that implements Countable 中的警告

MySQL:从左连接中仅选择一行,结果为多行

php - MYSQL 与 CONCAT 连接

sql - MySQL - 从多个具有相同结构但不同数据的表中选择数据

mysql,使用两个select

PHP 面向对象的数据库访问

sql - 根据列值选择记录

PHP数组输出到列表

php - 使用 PHP 从 MySQL 表进行计算

sql - 使用 SQL Server 插入具有自动增量的嵌套实体