简体   繁体   中英

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 ?

You can try with UNION :

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

SqlFiddle

问题是,如果您按cuisine_1过滤, cuisine_1丢失另一列的一些数据,因此您可以尝试通过为每一列获取一个SELECT DISTINCT ,然后合并两个数组并按array_unique过滤

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM