SQL 查询在 2 个表之间获取结果,第二个表有 3 种返回数据的可能性



尽管我的问题被警告为类似的标题,但我在这里找不到任何类似的问题。让我详细解释一下: 我有两个表(我正在使用 MySQL(,其中插入了这些值:

表产品:

id  name
1   TV
2   RADIO
3   COMPUTER

表销售额(product_id是引用产品(id(的FK(: id quantity product_id 1 50 2 2 100 3 3 200 3

电视还没有售出,收音机有1个销售(50个单位(,电脑有2个销售(100个单位中的一个(,另一个是200个单位(;

现在,我必须创建一个查询,我可以在其中显示产品及其销售情况,但有一些条件会使该任务变得困难:
1 - 如果没有销售,则明显显示 NULL;
2 - 如果有 1 笔销售,则显示该销售;
3 - 如果有超过 1 笔销售,则显示最新销售(我尝试使用函数 MAX(id( 使其简单, 但没有奏效(;

在上面的表格示例中,我希望在正确的SQL查询之后显示以下内容:

products.NAME sales.QUANTITY TV NULL RADIO 50 COMPUTER 200

我一直在尝试很多连接、内部连接等,但找不到我期望的结果。哪个 SQL 查询可以给出我期望的答案? 任何帮助将不胜感激。 谢谢。

希望下面的查询有效。

SELECT products.name, sl.quantity 
FROM products LEFT JOIN (
SELECT product_id, max(quantity) as quantity FROM sales GROUP BY product_id) sl
ON products.id = sl.product_id

在MySQL 8.0中,你可以做:

with m (product_id, max_id) as ( -- This is a CTE
select product_id, max(id) from sales group by product_id
)
select
p.name,
s.quantity
from products p
left join m on m.product_id = p.id
left join sales s on s.id = m.max_id

如果您有较旧的 MySQL,则可以使用表表达式:

select
p.name,
s.quantity
from products p
left join ( -- This is a table expression
select product_id, max(id) as max_id from sales group by product_id
) m on m.product_id = p.id
left join sales s on s.id = m.max_id  

最新更新