I’ve mysql database where data is column:
+----+-------+--------+--+
| ID | refID | data | |
+----+-------+--------+--+
| 1 | 1023 | aaaaaa | |
| 2 | 1024 | bbbbbb | |
| 3 | 1025 | cccccc | |
| 4 | 1023 | ffffff | |
| 5 | 1025 | gggggg | |
| 6 | 1022 | rrrrrr | |
+----+-------+--------+--+
I want this data to be shown in rows with duplicate values:
+----+-------+--------+--------+
| ID | refID | data | data2 |
+----+-------+--------+--------+
| 1 | 1023 | aaaaaa | ffffff |
| 2 | 1024 | bbbbbb | |
| 3 | 1025 | cccccc | gggggg |
| 4 | 1022 | rrrrrr | |
+----+-------+--------+--------+
Is it possible with PHP & MYSQL?
I tried mysql query group by refID but it’s not working.
2
Answers
Assuming there be at most 2 duplicates per
refID
, we can try using aggregation:Your expected
ID
column seems redundant, if you really need it then just addROW_NUMBER() OVER (ORDER BY some_col)
to the above query.You could use row_number in a subquery to give each refID group a specific number and then apply conditional aggregation in an outer query:
Consider the following data:
https://dbfiddle.uk/3LpgXlb9
Note, ID seems redundant to me and it can be removed from the select statements