mysql select max&通过...分组

时间:2016-06-11 18:35:51

标签: mysql

http://i64.tinypic.com/wb7y2b.png

那是我的桌子。

怎么做?我试过了,它只给出了1个最大exp1结果......

   "SELECT * FROM table1
WHERE (product_id=$id AND group=1) OR
 (product_id=$id AND group=1) OR
 (product_id=$id AND group=4) OR
 (product_id=$id AND group=7)
GROUP BY group"

3 个答案:

答案 0 :(得分:0)

尝试对max(product_id,exp1)

的in子句
select * 
from table1 
where   (product_id, exp1) in (
      select max(product_id), max(exp1) 
      from table1 
      group by `group`
      having group in (1,4,7)

如果您只想选择组和id = $ id,您可以

答案 1 :(得分:0)

您可以选择MAX(exp1)GROUP BY组,然后选择INNER JOIN table1获取其他详细信息,然后使用WHERE子句

过滤product_id
SELECT * 
FROM table1 T1 INNER JOIN
    (SELECT `group`,product_id,MAX(exp1) as max_exp1
     FROM table1 
     WHERE product_id = $id
     AND `group` in (1,4,7)
     GROUP BY `group`,product_id)T2
ON T1.exp1 = T2.max_exp1 
AND T1.`group` = T2.`group` 
AND T1.product_id = T2.product_id

答案 2 :(得分:0)

SELECT x.* 
  FROM my_table x
  JOIN 
     ( SELECT my_group
            , MAX(exp1) exp1 
         FROM my_table 
        WHERE product_id = 881 
        GROUP 
           BY my_group
     ) y 
    ON y.my_group = x.my_group 
   AND y.exp1 = x.exp1;