sql查询

krcsximq  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(255)

我开始学习sql(不是mysql,因为它在某些方面似乎有所不同),我遇到了这个问题,我不知道如何解决
我有以下表格:

CREATE TABLE products(
    product char(30),
    color   char(30)
);

INSERT INTO products (product, color)
VALUES 
("table","brown"),
("chair","brown"),
("shelf","brown"),
("table","black"),
("chair","white");

CREATE TABLE suppliers(
    supplier char(30),
    product char(30),
    color   char(30)
);

INSERT INTO suppliers (supplier, product, color)
VALUES 
("s1","chair","brown"),
("s1","door","brown"),
("s1","table","brown"),
("s1","table","black"),
("s1","shelf","brown"),
("s2","chair","brown"),
("s3","table","brown"),
("s3","table","black"),
("s3","chair","brown"),
("s3","chair","white"),
("s3","shelf","white");

我需要找到使用sql的供应商和数量的棕色产品,他们可以提供给商店和商店销售,按计数上升(棕色产品在产品表)。我从子查询和类似的内容开始:

select supplier,COUNT(pb.product)
from (select product from products where color = "brown") as pb, (select supplier, product from suppliers where color = "brown") as sb
where pb.product == sb.product;

但我想不出来,请帮帮我。
这些表格上的结果需要是:

supplier| no_of_products
-------------------------
   s2   |   1
   s3   |   2
   s1   |   3
kknvjkwl

kknvjkwl1#

看起来您需要简单的聚合:

select supplier, count(*) no_brown_products
from suppliers 
where color = 'brown'
group by supplier
2hh7jdfx

2hh7jdfx2#

这里有一个join查询,希望它能解决你的问题

SELECT supplier,COUNT(pb.product)
FROM product pb
INNER JOIN supliers sp ON sp.color = pb.color
WHERE color = 'brown'
GROUP BY supplier;
g6ll5ycj

g6ll5ycj3#

最后我需要的是:

select supplier, COUNT(s.product)
From suppliers s, products p
WHERE s.product = p.product and s.color = "brown" and p.color = "brown"
GROUP by supplier
order by COUNT(s.product);

相关问题