MYSQL - 分组依据和排序依据

时间:2016-05-27 07:46:09

标签: mysql sql

我有一张桌子:

ID    Field1    Field2    Field3
1     Apple     Fruit     Cheap
2     Apple     Fruit     Eatable
3     Apple     Food      Something
4     Banana    Fruit     Cheap
5     Banana    Food      Eatable
6     Cat       Pet       Weird
7     Cat       Pet       Friend
8     Cat       Pet       Amazing
9     Cat       Animal    Cheap

我希望获得不同的Field1,Field 2元素,并按Field3排序,包含" Cheap"。 我期待着这个:

ID    Field1    Field2    Field3
1     Apple     Fruit     Cheap
4     Banana    Fruit     Cheap
9     Cat       Animal    Cheap
3     Apple     Food      Something    
5     Banana    Food      Eatable
6     Cat       Pet       Weird

结果具有ID = 2,7,8的行被删除,因为ID = 2具有相同的field1,field2作为ID = 1而ID = 7,8具有相同的field1,field2作为ID = 6。 ID = 1且ID = 2具有相同的Field1和Field2。只有ID = 6,7,8中的一个进入具有不同的Field1,Field2的结果。

我试过"分组"和"按字段()"排序,但是对于"分组"所需的行被淘汰。例如,分组后ID = 1不存在且ID = 2行。

我目前的查询是:

select * from tbl
group by field1,field2
order by field(field3,"CHEAP") desc;

哪个只给我两行,其中field3 ="便宜" as" group by"正在考虑ID = 2而不是ID = 1

有人可以帮助我吗?

提前致谢。

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT t1.ID, t1.Field1, t1.Field2, t1.Field3
FROM mytable AS t1
JOIN (
  SELECT Field1, Field2, MAX(Field3) AS min_field3,
         COUNT(CASE WHEN Field3 = 'Cheap' THEN 1 END) AS cnt_cheap
  FROM mytable
  GROUP BY Field1, Field2
) AS t2 ON t1.Field1 = t2.Field1 AND 
           t1.Field2 = t2.Field2 AND
           t1.Field3 = IF(t2.cnt_cheap = 1, 'Cheap', min_field3)
ORDER BY FIELD(Field3, 'Cheap') DESC 

以上查询选择了“便宜货”。来自Field1, Field2组的记录,如果存在这样的记录,否则它会选择具有最大Field3值的记录。

答案 1 :(得分:1)

你也可以尝试这个

 select id,field1,field2,field3
 from tabel1 
 group by field3
 order by field1 DECS and field2 DECS