[英]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 |
+-----+-----------------+----------+
我尝试按具有store_id
0和4的template_title
按组获取记录。
然后我得到了这张唱片
+-----+----------+------+-----------+
| id | template_title | store_id |
+-----+----------+------+-----------+
| 1 | TEST_TITLE | 0 |
| 4 | TEST_ITEM | 0 |
| 5 | TEST_LOVE | 0 |
+-----+-----------------+----------+
但是我需要具有Group by的记录,但是如果store_id
不为0,则必须获取记录。 就像我需要这种类型的数据
+-----+----------+------+-----------+
| id | template_title | store_id |
+-----+----------+------+-----------+
| 1 | TEST_TITLE | 4 |
| 4 | TEST_ITEM | 0 |
| 5 | TEST_LOVE | 0 |
+-----+-----------------+----------+
表示如果我分组的话,我需要4
TEST_TITLE
。
我的意思是说,如果我按template_title
分组,我想优先考虑Store_id
这并非完全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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.