开发者

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

开发者 https://www.devze.com 2023-03-13 11:34 出处:网络
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:

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, col开发者_JS百科umn2 has duplicates and its ordered by column 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?


You need to do a union

select distinct column1 v from table union select distinct column2 v from table order by v


You could use something like this (sintax depends on db engine):

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


tbl1 COL1 | tbl2 COL2 | NEWCOL (The conclusion to be us)


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

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

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

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

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

------------- ------------- f

Auto DISTINCT, this work.

$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/>';
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消