How to merge several columns into one and remove duplicate mysql? Here is an example code:

$result = mysql_query ("SELECT CONCAT(channeltv,',',channeltv2,',',channeltv3,',',channeltv4) as output FROM igry"); while ( $itemm = @mysql_fetch_array( $result ) ) : echo $itemm['output']; endwhile; 

As a result, I get something like this: channel1, channel3, channel10, channel12 channel1 ,,, channel5, channel1, channel10, etc ...

Ie all in one line, a comma is displayed if the cell is empty and doubles are displayed.

And what was needed was this:

channel1

channel3

channel5

channel10

channel12

etc...

How to write such code?

  • select channeltv from igry UNION select channeltv2 from igry ... In general, we must look towards changing the structure of the database. storing several values ​​of the same nature in one column is not accepted - Mike
  • changing the table is not an option, it should be like this - Stas
  • and you can write a complete request with UNION, but I don’t quite understand how to get the final result - Stas
  • Well, you're the one that wrote a look to start to make a conclusion or not, but then suddenly I did not understand. And then add another union for each column - Mike
  • I don’t understand how to output them at the end in one column, now echo $ itemm ['output']; is displayed there, but what about your code? - Stas

2 answers 2

I think it's better to do it all in one line in PHP:

 $result = mysql_query ("SELECT CONCAT(channeltv,',',channeltv2,',',channeltv3,',',channeltv4) as output FROM igry"); while ( $itemm = @mysql_fetch_array( $result ) ) : echo implode("\n", array_unique(array_filter(explode(',', $itemm['output'])))); <--- тут было echo $itemm['output']; endwhile; 
  • and with doubles how to be? they will not be removed by this code - Stas
  • The duplicates will be deleted - for this there is a call to the function array_unique - SergeyLebedev

Anyone interested in finding a solution to this problem may be sloppy, but it works.

 $result = mysql_query ("SELECT channeltv as output FROM igry UNION (SELECT channeltv2 as output FROM igry) UNION (SELECT channeltv3 as output FROM igry) UNION (SELECT channeltv4 as output FROM igry) ORDER BY output"); echo '<select>'; while ( $itemm = @mysql_fetch_array( $result ) ) : echo '<option>'.$itemm['output'].'</option>'; endwhile; echo '</select>';