【问题标题】:Union 2 table with diff schema具有不同架构的联合 2 表
【发布时间】:2025-11-23 08:25:01
【问题描述】:

以下是要求和给定的表架构

使用表 1、表 2 和表 3 在 Canvas 中编写查询,仅适用于两个表中可用的书籍,条件如下

  • 必须是非小说类作品且评分高于 4.2 。
  • 引入一个使用价格来显示分组的列。
  • 联合表 3。

Table Schema

我能够解决第一点。但是我无法理解第 2 点和第 3 点。你们认为这是一个不正确的问题吗?

我的查询:

Select table2.book, table1.genre, table2.ratings, table2.reviews, table2.type, table2.price 
from table1 inner join table2 on table1.book_name = table2.book
where table1.genre = 'non-fiction' 
and table2.ratings > 4.2

【问题讨论】:

  • 用格式化的 CREATE TABLE 脚本替换您的表架构屏幕截图。
  • 我删除了不一致的数据库标签。请仅使用您真正使用的数据库进行标记。

标签: sql join union


【解决方案1】:

无法将具有不同列数的两个表合并。

UNION 是一个集合运算符,它在表中垂直组合数据。因此,列必须是相同的编号、相同的数据类型和相同的顺序。

如果你想使用 UNION,这里的技巧是对两个表中存在的额外列使用 NULL。你可以用这种方式匹配列数。

(select table2.book,table2.author,NULL as noOfCopies,table1.genre,table2.ratings,table2.reviews,table2.type,sum(table2.price) as totalprice
from table1 inner join table2 on table1.book_name = table2.book
where table1.genre = 'non-fiction'  and table2.ratings > 4.2 
group by table2.book, table1.genre, table2.ratings, table2.reviews,table2.type)
UNION
select NULL as book, author_name, noOfCopies, NULL as genre, NULL as ratings, NULL as reviews, NULL as type, NULL as totalprice from table3;

【讨论】:

    【解决方案2】:

    与table3联合,使用inner join将table2和table3与作者姓名联系起来

    Select table2.book, table1.genre, table2.ratings, table2.reviews, table2.type, sum(table2.price), sum(noofcopies)
    from table1 
    inner join table2 on table1.book_name = table2.book 
    inner join table3 on table2.author=table3.author_name
    where table1.genre = 'non-fiction' and table2.ratings > 4.2 
    group by table2.book, table1.genre, table2.ratings, table2.reviews,table2.type
    

    【讨论】:

    • 嗨,你能解释一下你的代码吗?就像我们如何合并表 3 一样?
    • 我觉得table3.noofcopies一定要总结,不能算。
    • table3 每个table2 可能包含不止一个匹配行。连接乘法将发生在sum(table2.price)
    最近更新 更多