有没有办法列出多列中不同的字段结果

时间:2019-07-14 21:02:56

标签: mysql sql

我有几张桌子,我想在其中查看其中多个字段的不同值。

例如。

ID | Category | sub_category | item

有没有一种方法可以为每个字段返回唯一的结果集?

本质上,我只想查看一个结果集中表中不同列的所有不同值。

我尝试过加入,但我需要结果彼此互斥。

enter image description here

每个返回的字段也不一定具有相同的匹配行数。

1 个答案:

答案 0 :(得分:1)

您可以只使用union all吗?

select distinct 'category', category
from t
union all
select distinct 'subcategory', subcategory
from t;

编辑:

如果要在不同的列中输入值:

select c.category, s.subcategory
from (select category, row_number() over (order by category) as seqnum
      from t
      group by category
     ) c full join
     (select subcategory, row_number() over (order by subcategory) as seqnum
      from t
      group by subcategory
     ) s
     on c.seqnum = s.seqnum;

您可以通过添加更多子查询和full join来将其扩展为其他列。

编辑II:

较旧的MySQL版本既不支持窗口函数也不支持full join。您可以执行类似的操作,枚举每个值,然后进行汇总:

select max(category) as category,
       max(subcategory) as subcategory
from ((select (@rnc := @rnc + 1), category, null as subcategory
       from (select distinct category from t
            ) c cross join
            (select @rnc := 0) params
      ) union all
      (select (@rns := @rns + 1), null as category, subcategory
       from (select distinct subcategory from t
            ) s cross join
            (select @rns := 0) params
      )
     ) sc
group by rn;