首先出现返回结果的顺序

时间:2011-05-24 14:22:35

标签: sql

我有两个表,希望根据表a中的引用ID从表b中获取tech_tag:

select b.dbid, b.technology_tag 
from tblConnect a, tblSites b 
where a.Site_DBID = 2 
and a.Related_Site_DBID = 1 
and (b.dbid = a.bsc_tag_dbid or b.dbid = a.related_bsc_dbid or b.dbid = a.related_msc_dbid)

我想要的是根据第一次出现(在where子句中)对返回的行进行排序

1st- b.dbid = a.bsc_tag_dbid  
2cnd- b.dbid = a.related_bsc_dbid 
3rd- b.dbid = a.related_msc_dbid

有没有人知道如何做到这一点?

1 个答案:

答案 0 :(得分:1)

首先,在执行连接时应切换到使用实际的JOIN子句。也就是说,这个ORDER BY子句应该做你想要的:

SELECT
    B.dbid,
    B.technology_tag
FROM tblConnect A
INNER JOIN tblSites B ON
    B.dbid IN (A.bsc_tag_dbid, A.related_bsc_dbid, A.related_msc_dbid)
WHERE
    A.Site_DBID = 2 AND
    A.Related_Site_DBID = 1
ORDER BY
    CASE
        WHEN B.dbid = A.bsc_tag_dbid THEN 1
        WHEN B.dbid = A.related_bsc_dbid THEN 2
        WHEN B.dbid = A.related_msc_dbid THEN 3
        ELSE 4   -- Not really necessary, but I always use an ELSE when I use CASE
    END