2
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.

如何编写这个查询?

4

4 回答 4

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.

于 2013-10-01T12:16:08.293 回答
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

于 2013-10-01T12:16:19.037 回答
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 列的聚合函数,那么您需要在两列上进行分组

于 2013-10-01T12:17:17.813 回答
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
于 2013-10-01T12:25:06.300 回答