Reputation: 128
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.
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.
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.
I meant to say i want to give Priority to Store_id
if i Group by template_title
Upvotes: 1
Views: 74
Reputation: 1269503
This isn't exactly a 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
:
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);
Upvotes: 1