I have a query which looks like this. The problem is that the entire query is grouped which is not desired.
select `col_1`, `col_2`, `col_3`
from `mytable`
where (
`col_4` LIKE '%abc%'
or `col_5` LIKE '%def%'
or `col_6` LIKE '%2020%'
)
GROUP BY col_1 # << this groups entire query
Instead, I am trying to aim for a particular column to be grouped like this.
I need to group col_1 for this specific condition col_6 LIKE '%zzz%'
select `col_1`, `col_2`, `col_3`
from `mytable`
where (
`col_4` LIKE '%abc%'
or `col_5` LIKE '%def%'
or (`col_6` LIKE '%2020%' GROUP BY col_1) #<< need this GROUP BY col_1
)
Heres an example of the output. Col_6 has 3 rows of 2020 and since 2 of those rows have the same value of "aaaa" in col_1, those 2 rows would need to be grouped. The value of col_3 for grouped items would just be the last item in the list.
+-------+-------+-------+-------+
| col_1 | col_2 | col_3 | col_6 |
+-------+-------+-------+-------+
| aaaa | abc01 | red | 2020 |
| aaaa | abc01 | blu | 2020 |
| aaaa | abc01 | blu | 2019 |
| aabb | abc01 | grey | 2020 |
| bbbb | abc01 | purp | 2019 |
| cccc | abc01 | white | 2018 |
+-------+-------+-------+-------+
This query will have pagination and is intended for use in Laravel. Because of this UNION
will not work because this interferes with Laravels pagination.
This would be the desired outcome
+-------+-------+-------+-------+
| col_1 | col_2 | col_3 | col_6 |
+-------+-------+-------+-------+
| aaaa | abc01 | blu | 2020 |
| aaaa | abc01 | blu | 2019 |
| aabb | abc01 | grey | 2020 |
| bbbb | abc01 | purp | 2019 |
| cccc | abc01 | white | 2018 |
+-------+-------+-------+-------+
this groups the condition but I would need on top of this all the other items
select `col_1`, `col_2`, `col_3`
from `mytable`
where (
`col_4` LIKE '%abc%'
or `col_5` LIKE '%def%'
or `col_6` LIKE '%2020%'
)
GROUP BY col_1
HAVING `col_6` LIKE '%2020%'