简体   繁体   English

MySQL选择不同的多列遍历结果

[英]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: 我正在尝试从2个不同的列中选择没有重复的类别,表格看起来像这样:

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 预期结果是每个类别仅一次,无论它来自cuisine_1还是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 : 您可以尝试使用UNION

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

SqlFiddle SqlFiddle

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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