user327685
user327685

Reputation: 129

Mysql select distinct multiple columns loop through results

I'm trying to select categories without duplicates from 2 different columns, the table looks something like this:

cuisine_1    cuisine_2
----------------------
italian       french
italian       chinese
japanese      german
western
french        german
international
western       sushi
sushi         steak
steak
chinese
vietnamese    chinese

Expected result is every category only once where it doesn't matter if it came from cuisine_1 or cuisine_2

I tried like so:

$categories=mysqli_query($link,"select distinct cuisine_1,cuisine_2 AS cuisine_unique from table");


while($row_cu=mysqli_fetch_array($categories)){
       echo $row_cu['cuisine_unique']."<br>";
    }

Without any luck so far. Do I have to group the results first, or what am I doing wrong ?

Upvotes: 0

Views: 1389

Answers (2)

MamaWalter
MamaWalter

Reputation: 2113

You can try with UNION:

(SELECT distinct cuisine_1 AS cuisine_unique FROM table) UNION (SELECT distinct cuisine_2 FROM table)

SqlFiddle

Upvotes: 2

The problem is if you filter by cuisine_1 you'll be losing some data from the other column, so you can try by getting one SELECT DISTINCT for each column and then merge both arrays and filter by array_unique

Upvotes: 0

Related Questions