我有以下查询:
SELECT * FROM quotes
INNER JOIN quotes_panels ON quotes.wp_user_id = quotes_panels.ID
WHERE quotes.created >= '$startDate'
AND quotes.created <= '$endDate' AND quotes.wp_user_id != '0'
此查询可以从同一个用户生成多行(quotes.wp_user_id),但我只想显示具有最大屋顶区域的行(quotes.roofarea)。
但是,当我添加GROUP BY quotes.wp_user_id时,它会自动采用最低的quotes.ID行而不是具有最大quotes.roofarea的行。将ORDER BY quotes.roofarea DESC添加到查询的末尾时,它会对整个结果进行排序,而不仅仅是“GROUP BY”的结果。
有人可以协助获得查询所需的结果吗?
由于
答案 0 :(得分:0)
您必须先对行进行排序。
SELECT * FROM (SELECT * FROM quotes
INNER JOIN quotes_panels ON quotes.wp_user_id = quotes_panels.ID
WHERE quotes.created >= '$startDate'
AND quotes.created <= '$endDate' AND quotes.wp_user_id != '0'
ORDER BY quotes.roofarea DESC) a
GROUP BY a.wp_user_id
答案 1 :(得分:0)
在MySQL中GROUP BY
在ORDER BY
之前完成,因此您需要在两个查询中执行此操作:
SELECT * FROM
(SELECT * FROM quotes
INNER JOIN quotes_panels ON quotes.wp_user_id = quotes_panels.ID
WHERE quotes.created >= '$startDate'
AND quotes.created <= '$endDate' AND quotes.wp_user_id != '0'
ORDER BY quotes.roofarea DESC) AS subset
GROUP BY subset.wp_user_id
答案 2 :(得分:0)
您必须添加如下聚合函数:
SELECT *, MAX(quotes.roofarea) FROM quotes
INNER JOIN quotes_panels ON quotes.wp_user_id = quotes_panels.ID
WHERE quotes.created >= '$startDate'
AND quotes.created <= '$endDate' AND quotes.wp_user_id != '0'
GROUP BY quotes.wp_user_id
在这里阅读更多相关信息:
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
答案 3 :(得分:0)
试试这个
SELECT * FROM quotes
INNER JOIN quotes_panels ON quotes.wp_user_id = quotes_panels.ID
WHERE quotes.created >= '$startDate'
AND quotes.created <= '$endDate' AND quotes.wp_user_id != '0'
AND quotes.roofarea = (SELECT MAX(q.roofarea) FROM quotes q WHERE q.wp_user_id = quotes.wp_user_id)
GROUP BY quotes.wp_user_id
立即检查