SQL:使用group by时无法按降序获取值

时间:2011-12-20 12:36:34

标签: php mysql phpmyadmin

使用以下查询加入和检索两个表中的值。它按降序显示值。

Leads
63697       Ben
63698       Ben
63699       Ben
63700       Ben
63701       Ben


log

2   63697       Ben         10%     Qualifying
3   63697       Ben         20%     Qualifying
4   63697       Ben         30%     Qualifying
6   63698       Ben         30%     Qualifying
8   63698       Ben     80%     Quoted
10  63698       Ben         70%     Quoted

我想要显示,

63697       Ben         30%     Qualifying
63698       Ben         70%     Quoted
63699       Ben
63700       Ben
63701       Ben

问题在于,当我使用查询时,

SELECT leads.id,leads.name, log.prob, log.current_stage FROM leads LEFT JOIN log ON log.leadid = leads.id WHERE leads.name = '$name' ORDER BY log.id DESC

以降序显示日志表的所有详细信息。但是当我尝试将它们分组时,

SELECT leads.id,leads.name, log.prob, log.current_stage FROM leads LEFT JOIN log ON log.leadid = leads.id WHERE leads.name = '$name' GROUP BY log.leadid ORDER BY log.id DESC

它从日志表中按升序抓取值

63697       Ben         10%     Qualifying
63698       Ben         30%     Qualifying
63699       Ben
63700       Ben
63701       Ben

有人可以告诉我这里我做错了什么吗?

2 个答案:

答案 0 :(得分:2)

SELECT * FROM (
SELECT leads.id,leads.name, log.prob, log.current_stage, log.id AS logid FROM leads LEFT JOIN log ON log.leadid = leads.id WHERE leads.name = '$name' GROUP BY log.leadid
) ORDER BY logid DESC

经常看到这个,只需将它包装在一个超级查询中,如图所示。

答案 1 :(得分:0)

您按log.id排序,这不是您选择的字段。您不能这样做,因为在SELECT指令之后评估ORDER BY。

为ORDER BY leads.id更改ORDER BY log.id,这是我在SELECT指令中看到的唯一标识符。