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 |
+-----+-----------------+----------+
但我需要有分组依据的记录,但如果 store_id
不为 0,则必须获取记录。
就像我需要这种类型的数据一样
+-----+----------+------+-----------+
| id | template_title | store_id |
+-----+----------+------+-----------+
| 1 | TEST_TITLE | 4 |
| 4 | TEST_ITEM | 0 |
| 5 | TEST_LOVE | 0 |
+-----+-----------------+----------+
意味着如果我分组,我需要 TEST_TITLE
of 4
。
我的意思是说,如果我按 template_title
分组,我想将 Priority 赋予 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);
关于mysql - 在 mysql 查询中按条件分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25568331/