SELECT DISTINCT
t1.name as t1_name,
MAX(t1.unit) as t1_unit,
MAX(t1.id_producer_goods) AS hi_id_producer_goods,
t2.name as t2_name
FROM Table1 t1
left join Table2 t2 on t1.id_web_site=t2.id_web_site
WHERE t1.id='23'
GROUP BY t1.name
当我运行查询时,出现以下错误:
Column 'Table2.name' is invalid in the select list because it is not contained
in either an aggregate function or the GROUP BY clause.
如何撰写此查询?
答案 0 :(得分:5)
错误很明显,要么使用t2.name
的聚合函数,要么将其添加到GROUP BY
,这取决于您要查找的所需结果:
SELECT
t1.name as t1_name,
t2.name as t2_name,
MAX(t1.unit) as t1_unit,
MAX(t1.id_producer_goods) AS hi_id_producer_goods
FROM Table1 hi
left join Table2 t2 on t1.id_web_site=t2.id_web_site
WHERE t1.id='23'
GROUP BY t1.name, t2.name;
错误是有道理的,因为它必须知道每个t2.name
组的t1.name
选择哪个值?应该选择max
,min
等,否则GROUP BY
。
另外,DISTINCT
删除GROUP BY
不需要{。}}。
答案 1 :(得分:1)
SELECT
t1.name as t1_name,
MAX(t1.unit) as t1_unit,
MAX(t1.id_producer_goods) AS hi_id_producer_goods,
t2.name as t2_name FROM Table1 hi
left join Table2 t2 on t1.id_web_site=t2.id_web_site
WHERE
t1.id='23'
GROUP BY t1.name,t2.name
您需要按AGG功能中未使用的所有字段进行分组。等MAX
答案 2 :(得分:0)
试试这个
SELECT
DISTINCT
t1.name as t1_name,
MAX(t1.unit) as t1_unit,
MAX(t1.id_producer_goods) AS hi_id_producer_goods,
t2.name as t2_name FROM Table1 hi
left join Table2 t2 on t1.id_web_site=t2.id_web_site
WHERE
t1.id='23'
GROUP BY t1.name,t2.name
您正在使用具有2列的聚合函数,然后您需要在两列上进行分组
答案 3 :(得分:0)
我认为这里不需要DISTINCT关键字。
SELECT
t1.name as t1_name,
MAX(t1.unit) as t1_unit,
MAX(t1.id_producer_goods) AS hi_id_producer_goods,
t2.name as t2_name
FROM Table1 t1
left join Table2 t2 on t1.id_web_site=t2.id_web_site
WHERE t1.id='23'
GROUP BY t1.name,t2.name