我有这个查询
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
答案 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
似乎不是问题。