0

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 ?

3
  • tried to put these two in a single array und use array_unique() on it? Commented Nov 12, 2014 at 18:38
  • 1
    possible duplicate of MySQL: Get unique values across multiple columns in alphabetical order Commented Nov 12, 2014 at 18:42
  • You probably want a union as MamaWalter is suggesting. Distinct will get you distinct rows, not columns. This means that a single column may repeat because all columns in a row have to be unique for the row to be unique which is what you are seeing here. The combination of column 1 and column 2 is unique. Commented Nov 12, 2014 at 18:46

2 Answers 2

2

You can try with UNION:

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

SqlFiddle

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.