2014-08-29 83 views
1
Sample Database Table: 
+-----+----------+------+-----------+ 
| id | template_title | store_id | 
+-----+----------+------+-----------+ 
| 1 |  TEST_TITLE | 0   | 
| 2 |  TEST_TITLE | 4   | 
| 3 |  TEST_TITLE | 2   | 
| 4 |  TEST_ITEM | 0   | 
| 5 |  TEST_LOVE | 0   | 

+-----+-----------------+----------+ 

我尝试通过集团具有store_id 0和4集团通过与MySQL查询条件

template_title获取记录,然后我得到这个纪录

+-----+----------+------+-----------+ 
    | id | template_title | store_id | 
    +-----+----------+------+-----------+ 
    | 1 |  TEST_TITLE | 0   | 
    | 4 |  TEST_ITEM | 0   | 
    | 5 |  TEST_LOVE | 0   | 

    +-----+-----------------+----------+ 

,但我需要有记录组但如果有store_id不是0那么它必须得到记录。 像我需要这种类型的数据的

 +-----+----------+------+-----------+ 
     | id | template_title | store_id | 
     +-----+----------+------+-----------+ 
     | 1 |  TEST_TITLE | 4   | 
     | 4 |  TEST_ITEM | 0   | 
     | 5 |  TEST_LOVE | 0   | 

     +-----+-----------------+----------+ 

意味着我需要的4TEST_TITLE如果我组通过。

我的意思是说我想给优先Store_id如果我通过集团template_title

+0

对于'store_id' 4为什么ID = 1何不的对应行值id = 2? – 2014-08-29 12:35:26

+2

您选择三个值:template_title,id和store_id。在按template_title进行分组时,您必须决定选择哪个ID和哪个store_id。显然你决定MAX(store_id) - 它已经回答了你的问题。那么你想展示什么样的标识?为什么要显示一个ID? – 2014-08-29 12:36:45

+0

我的意思是说,如果我通过'template_title'分组,我想优先考虑Store_id – 2014-08-30 06:12:35

回答

2

这不是完全是group by。您希望根据业务规则对行进行优先排序。规则似乎与4是选择该行第一,然后将一个用0。认为最简单的方法是使用union all

select id, template_title, store_id 
from databasetable 
where store_id = 4 
union all 
select id, template_title, store_id 
from databasetable 
where store_id = 0 and 
     not exists (select 1 from template_title where store_id = 4); 
0

您可以使用MAX获得列的最大价值:

SELECT 
    id, 
    template_title, 
    MAX(store_id) 
FROM myTable 
GROUP BY template_title