订购Group BY

时间:2014-08-14 12:33:32

标签: mysql sql

关于这个主题有很多问题,仍然无法找到一种方法来使这项工作。

我正在做的查询是:

SELECT `b`.`ads_id`     AS `ads_id`,
  `b`.`bod_bedrag`      AS `bod_bedrag`,
  `a`. `ads_naam`       AS `ads_naam`,
  `a`.`ads_url`         AS `ads_url`,
  `a`.`ads_prijs`       AS `ads_price`,
  `i`.`url`             AS `img_url`,
  `c`.`url`             AS `cat_url`
FROM `ads_market_bids`  AS `b`
INNER JOIN `ads_market` AS `a`
ON `b`.`ads_id` = `a`.`id`
INNER JOIN `ads_images` AS `i`
ON `b`.`ads_id` = `i`.`ads_id`
INNER JOIN `ads_categories` AS `c`
ON `a`.`cat_id`       = `c`.`id`
WHERE `i`.`img_order` = '0'
AND `b`.`u_id`        = '285'
GROUP BY `b`.`ads_id`
HAVING MAX(b.bod_bedrag)
ORDER BY `b`.`bod_bedrag` ASC

但是,我一直看到的问题是我需要在GROUP BY发生之前对b.bod_bedrag进行排序。不知道如何解释它。

我现在得到的bod_bedrag是表中出价最低的。我需要最高的。

尝试过所有事情,甚至尝试不使用DISTINCT进行分组。这也不起作用。尝试按max,我知道或可以在互联网上找到的所有内容。

图像1是没有分组的情况。订单工作很棒(ofc)。 No Group By  图像2与group by。如您所见,最低出价被视为bod_bedrag。我需要最高的。 With Group By

3 个答案:

答案 0 :(得分:3)

根据您想要的输出判断:

  SELECT amb.ads_id,
         MAX(amb.bod_bedrag) max_bod_bedrag,
         am.ads_naam,
         am.ads_url,
         am.ads_prijs ads_price,
         ai.url img_url,
         ac.url cat_url
    FROM ads_market_bids amb 
    JOIN ads_images ai 
      ON ai.ads_id = amb.ads_id
     AND ai.img_order = 0
    JOIN ads_market am 
      ON am.id = amb.ads_id 
    JOIN ads_categories ac
      ON ac.id = am.cat_id 
   WHERE amb.u_id = 285 
GROUP BY amb.ads_id, 
         am.ads_naam,
         am.ads_url,
         am.ads_prijs,
         ai.url,
         ac.url
ORDER BY max_bod_bedrag ASC

我还删除了所有不必要的回调和列别名到同名。 您的HAVING没有做任何事情,因为所有群组都有' MAX(amb.bod_rag)

答案 1 :(得分:1)

一种方法是模拟row_number()(MySQL没有),但它允许通过记录进行选择,而不是通过可能来自不同源记录的聚合。它的工作原理是向每行添加变量(增加行数)然后,使用有序子查询将这些变量设置为1,以获得最高b。{{1每个bod_bedragb b ads_id, all other rows per ads_id`获得更高的RN值。最后,我们过滤RN = 1(这相当于包含最高出价值的记录)

.

你甚至可以关闭那个愚蠢的GROUP BY扩展,详情请参见手册页: MySQL Extensions to GROUP BY

答案 2 :(得分:1)

select distinct `b`.`ads_id` as `ads_id`, max(`b`.`bod_bedrag`) as `bod_bedrag`, 
`a`.`ads_naam` as `ads_naam`, `a`.`ads_url` as `ads_url`, `a`.`ads_prijs` as `ads_price`,
`i`.`url` as `img_url`, `c`.`url` as `cat_url` 
 from `ads_market_bids` as `b` 
   inner join `ads_market` as `a` on `b`.`ads_id` = `a`.`id` 
   inner join `ads_images` as `i` on `b`.`ads_id` = `i`.`ads_id` 
   inner join `ads_categories` as `c` on `a`.`cat_id` = `c`.`id` 
 where `i`.`img_order` = '0' and `b`.`u_id` = '285' 
 group by b.ads_id, a.ads_naam, a.ads_url, a.ads_prijs, i.url, c.url