简体   繁体   English

从一个表中的同一表的2列中检索DISTINCT值

[英]Retrieving DISTINCT values from 2 columns in same table as one ordered list

I would like to take two columns of data in the same table, and return the unique records from both in an ordered list. 我想在同一张表中使用两列数据,并在有序列表中返回两列的唯一记录。 I tried this: 我试过这个:

SELECT DISTINCT column1,column2 FROM table ORDER BY column1 ASC

However this obviously returns both columns, column2 has duplicates and its ordered by column 1. 但是,这显然返回了两个列,column2具有重复项,并且按列1对其进行了排序。

I want to receive something like 我想收到类似

Abcde [column1]
Beefr [column2]
Ceeed [column1]
Desss [column1]
...etc

Is this possible? 这可能吗? I'm using PHP too if this helps? 如果这有帮助,我也使用PHP?

You need to do a union 你需要工会

select distinct column1 v from table union select distinct column2 v from table order by v 从表联合中选择不重复column1 v从表顺序中选择不重复column2 v

tbl1 COL1 | tbl1 COL1 | tbl2 COL2 | tbl2 COL2 | NEWCOL (The conclusion to be us) NEWCOL(结论就是我们)


a ------------- a ------------- a a ------------- a ------------- a

b ------------- b ------------- b b ------------- b ------------- b

c ------------- d ------------- c c ------------- d ------------- c

e ------------- f ------------- d e ------------- f ------------- d

------------- ------------- e ------------- ------------- e

------------- ------------- f - - - - - - - - - - - - - - F

Auto DISTINCT, this work. 自动DISTINCT,这项工作。

$Sql="SELECT COL1 AS NEWCOL FROM tbl1 UNION SELECT COL2 FROM tbl2 ORDER BY NEWCOL ASC";

    $q=mysql_query($Sql) or die(mysql_error());
        while($rs=mysql_fetch_array($q)){
            echo $rs['NEWCOL'].'<br/>';
        }

You could use something like this (sintax depends on db engine): 您可以使用类似以下内容(sintax取决于db引擎):

SELECT DISCTINCT column
FROM
   ( 
    SELECT column1 as column FROM table
    UNION
    SELECT column2 as column FROM table
   )
ORDER BY column ASC

Refer to you dbms manual to check sintax on UNION clause 请参考dbms手册以检查UNION子句的正弦

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

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