如何将选择结果与另一个表联接?
示例:生成每种产品类型的合计值的两列表格
SELECT product_type, SUM(value) AS total from table1
WHERE something_something_is_true
GROUP BY product_type;
另一个名为 table2 的表具有产品类型的文字说明
product_type | description | more columns
---------------------------------------
1 | ....................
2 | ....................
如何将description
列与上述选择结果结合起来,以使结果表看起来像这样?
product_type | total | description
---------------------------------
1 | 589 | stationary
2 | 234 | closing
答案 0 :(得分:1)
将查询用作派生表,然后将其描述表联接到该表。
select t1.*, t2.description
from (
SELECT product_type, SUM(value) AS total
from table1
WHERE ...
GROUP BY product_type
) t1
join table2 t2 on t1.product_type = t2.product_type
答案 1 :(得分:1)
您可以将子查询用作表表达式:
SELECT t1.product_type, total, description
FROM (SELECT product_type, SUM(value) AS total
FROM table1
WHERE something_something_is_true
GROUP BY product_type) t1
JOIN table2 t2 ON t1.product_type = t1.product_type
答案 2 :(得分:0)
您可以这样做:
SELECT t1.product_type, SUM(value) AS total,
MAX(t2.description)
FROM table1 t1 LEFT JOIN
table2 t2
ON t2.product_type = t1.product_type
WHERE something_something_is_true
GROUP BY t1.product_type;