对查询返回的列进行排序

时间:2013-07-11 12:09:05

标签: mysql sql oracle

我有这个查询

SELECT DISTINCT RE1.NAME AS NAME1,RE2.NAME AS NAME2 
FROM RATING R1,RATING R2,REVIEWER RE1,REVIEWER RE2
WHERE R1.RID > R2.RID 
  AND R1.MID  = R2.MID 
  AND RE1.RID = R1.RID 
  AND RE2.RID = R2.RID;

输出

NAME1     NAME2

CHRIS     BRITTANY
ASHLEY    CHRIS
JAMES     ELIZABETH

我想以这样的方式返回表格,即行按字母顺序排列,即输出应为:

NAME1     NAME2

BRITTANY   CHRIS
ASHLEY     CHRIS
ELIZABETH  JAMES

1 个答案:

答案 0 :(得分:10)

您可以使用least()greatest()功能:

SELECT DISTINCT least(RE1.NAME, re2.name) AS NAME1, greatest(re1.name, RE2.NAME) AS NAME2 
FROM RATING R1,RATING R2,REVIEWER RE1,REVIEWER RE2
WHERE R1.RID > R2.RID 
  AND R1.MID  = R2.MID 
  AND RE1.RID = R1.RID 
  AND RE2.RID = R2.RID;

您还应该学习正确的join语法:

SELECT DISTINCT least(RE1.NAME, re2.name) AS NAME1, greatest(re1.name, RE2.NAME) AS NAME2 
from rating r1 join
     rating r2
     on R1.RID > R2.RID AND R1.MID  = R2.MID and
     reviewer re1
     on RE1.RID = R1.RID join
     reviewer re2
     on RE2.RID = R2.RID  ;

编辑:

如果您的数据库不支持这两个函数,您可以使用case语句轻松执行相同的操作:

select distinct (case when RE1.NAME < re2.name then re1.name else re2.name end) AS NAME1,
       (case when RE1.NAME < re2.name then re2.name else re1.name end) as NAME2
. . . 

关于NULL的问题。原始数据已填充名称,并且联接都是内部联接,因此NULL似乎不是问题。