[英]Group by with condition in mysql query
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 |
+-----+-----------------+----------+
i try to get record by Group by template_title
having store_id
0 and 4. 我尝试按具有
store_id
0和4的template_title
按组获取记录。
then i got this record 然后我得到了这张唱片
+-----+----------+------+-----------+
| id | template_title | store_id |
+-----+----------+------+-----------+
| 1 | TEST_TITLE | 0 |
| 4 | TEST_ITEM | 0 |
| 5 | TEST_LOVE | 0 |
+-----+-----------------+----------+
but i need record having Group by but if there store_id
is not 0 then it must be get record. 但是我需要具有Group by的记录,但是如果
store_id
不为0,则必须获取记录。 like i need this type of data 就像我需要这种类型的数据
+-----+----------+------+-----------+
| id | template_title | store_id |
+-----+----------+------+-----------+
| 1 | TEST_TITLE | 4 |
| 4 | TEST_ITEM | 0 |
| 5 | TEST_LOVE | 0 |
+-----+-----------------+----------+
means i need TEST_TITLE
of 4
if i group by. 表示如果我分组的话,我需要
4
TEST_TITLE
。
I meant to say i want to give Priority to Store_id
if i Group by template_title
我的意思是说,如果我按
template_title
分组,我想优先考虑Store_id
This isn't exactly a group by
. 这并非完全
group by
。 You want to prioritize the rows, based on business rules. 您想根据业务规则对行进行优先排序。 The rule appears to be select the row with 4 first, and then the one with 0. It think the easiest way is using
union all
: 规则似乎是首先选择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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.