如何使用组和多个连接进行查询
how to make query with group and multiple joins
你好,我需要了解一下。
我有 3 个表:
产品
id_product
name
1
car
2
plane
3
bike
数量
id_product
quantity
1
10
2
17
3
5
价格
id_product
id_group
price
1
1
5.00
1
2
6.00
1
3
7.00
2
1
10.00
2
2
11.00
2
3
12.00
3
1
20.00
3
2
21.00
3
3
22.00
通过查询我希望得到这样的结果:
name
price1
price2
price3
quantity
car
5.00
6.00
7.00
10
plane
10.00
11.00
12.00
17
bike
20.00
21.00
22.00
5
我不能以这个结果为目标我的查询是:
SELECT
product.name,price.price,quantity.quantity
FROM product
LEFT JOIN price
ON product.id_product = price.id_product
WHERE price.id_group = 1
LEFT JOIN price
ON product.id_product = price.id_product
WHERE price.id_group = 2
LEFT JOIN price
ON product.id_product = price.id_product
WHERE price.id_group = 3
LEFT JOIN quantity
ON product.id_product = quantity.id_product
首先,在tableprice
中使用条件聚合获取价格,然后加入:
SELECT p.name, t.price1, t.price2, t.price3, q.quantity
FROM products p
LEFT JOIN quantity q ON q.id_product = p.id_product
LEFT JOIN (
SELECT id_product,
MAX(CASE WHEN id_group = 1 THEN price END) price1,
MAX(CASE WHEN id_group = 2 THEN price END) price2,
MAX(CASE WHEN id_group = 3 THEN price END) price3
FROM price
GROUP BY id_product
) t ON t.id_product = p.id_product
你好,我需要了解一下。 我有 3 个表:
产品
id_product | name |
---|---|
1 | car |
2 | plane |
3 | bike |
数量
id_product | quantity |
---|---|
1 | 10 |
2 | 17 |
3 | 5 |
价格
id_product | id_group | price |
---|---|---|
1 | 1 | 5.00 |
1 | 2 | 6.00 |
1 | 3 | 7.00 |
2 | 1 | 10.00 |
2 | 2 | 11.00 |
2 | 3 | 12.00 |
3 | 1 | 20.00 |
3 | 2 | 21.00 |
3 | 3 | 22.00 |
通过查询我希望得到这样的结果:
name | price1 | price2 | price3 | quantity |
---|---|---|---|---|
car | 5.00 | 6.00 | 7.00 | 10 |
plane | 10.00 | 11.00 | 12.00 | 17 |
bike | 20.00 | 21.00 | 22.00 | 5 |
我不能以这个结果为目标我的查询是:
SELECT
product.name,price.price,quantity.quantity
FROM product
LEFT JOIN price
ON product.id_product = price.id_product
WHERE price.id_group = 1
LEFT JOIN price
ON product.id_product = price.id_product
WHERE price.id_group = 2
LEFT JOIN price
ON product.id_product = price.id_product
WHERE price.id_group = 3
LEFT JOIN quantity
ON product.id_product = quantity.id_product
首先,在tableprice
中使用条件聚合获取价格,然后加入:
SELECT p.name, t.price1, t.price2, t.price3, q.quantity
FROM products p
LEFT JOIN quantity q ON q.id_product = p.id_product
LEFT JOIN (
SELECT id_product,
MAX(CASE WHEN id_group = 1 THEN price END) price1,
MAX(CASE WHEN id_group = 2 THEN price END) price2,
MAX(CASE WHEN id_group = 3 THEN price END) price3
FROM price
GROUP BY id_product
) t ON t.id_product = p.id_product