mysql GROUP BY如果这行table.field> 0

时间:2014-06-05 16:52:59

标签: mysql group-by conditional-statements

我如何GROUP BY entry_category if entry_category > 0

| entry_id | entry_title | entry_category |
-------------------------------
| 1        | xxx         | 6       |
| 2        | xxx         | 4       |
| 3        | xxx         | 6       |
| 4        | xxx         | 0       |
| 5        | xxx         | 0       |
| 6        | xxx         | 6       |
| 7        | xxx         | 4       |
| 8        | xxx         | 7       |

我想设置托管类别,不显示重复

| 1        | xxx         | 6       |
| 2        | xxx         | 4       |
| 4        | xxx         | 0       |
| 5        | xxx         | 0       |
| 8        | xxx         | 7       |

2 个答案:

答案 0 :(得分:1)

这是一种方法,但可能有更好的方法。我把表名称作为test

select 
entry_id,
entry_title,
entry_category
from
(
  (
    select
    t1.entry_id,
    t1.entry_title,
    t1.entry_category
    from test t1
    left join test t2
    on t1.entry_category = t2.entry_category
    AND t1.entry_id < t2.entry_id
    where t1.entry_category <> 0 
    group by t1.entry_category
  )
  union all
  (
    select entry_id,entry_title,entry_category from test 
    where entry_category = 0
  )
)x
order by entry_id

<强> DEMO

答案 1 :(得分:0)

这对我很有用:

    SELECT * FROM entrys 
    WHERE entry_category> 0
    GROUP BY  entry_category
  UNION
    SELECT * FROM entrys 
    WHERE entry_category= 0

做得好。