2011-10-16 58 views
0

對於搜索功能,我想返回三種類型的結果,所以我查詢了三次。或許,這將是更好的JOIN或UNION查詢到一個,但如何..如何結合同一表中的三個「select distinct」

string sql1 = "SELECT DISTINCT area, CHARINDEX(@ss, area) FROM rgmaplocation WHERE area LIKE '%' + @ss + '%' ORDER BY CHARINDEX(@ss, area) "; 
string sql2 = "SELECT DISTINCT compound, CHARINDEX(@ss, compound) FROM rgmaplocation WHERE compound LIKE '%' + @ss + '%' ORDER BY CHARINDEX(@ss, compound) "; 
string sql3 = "SELECT DISTINCT streetname, CHARINDEX(@ss, streetname) FROM rgmaplocation WHERE streetname LIKE '%' + @ss + '%' ORDER BY CHARINDEX(@ss, streetname)"; 

回答

3

Mikael Eriksson's solution是好的,如果你不介意區域,化合物和streetname混合起來。如果你想要讓他們分開,在這裏你去

WITH C(No,Loc, Idx) AS 
(
    SELECT DISTINCT 1,area, CHARINDEX('g', area) 
    FROM rgmaplocation 
    WHERE area LIKE '%g%' 
    UNION 
    SELECT DISTINCT 2,compound, CHARINDEX('g', compound) 
    FROM rgmaplocation 
    WHERE compound LIKE '%g%' 
    UNION 
    SELECT DISTINCT 3,streetname, CHARINDEX('g', streetname) 
    FROM rgmaplocation 
    WHERE streetname LIKE '%g%' 
) 
SELECT No,Loc, Idx 
FROM C 
ORDER BY No,Idx 
+0

這是完美的工作。謝謝 :) – Jesper

1

使用UNION,就像你說的,應該是這樣的:

string sqlAll = string.Format("{0} UNION {1} UNION {2}", sql1, sql2, sql3); 
+0

SELECT DISTINCT區,CHARINDEX( 'G',區)距離rgmaplocation WHERE面積LIKE '%G%' ORDER BY CHARINDEX( 'G',區)UNION SELECT DISTINCT化合物,CHARINDEX('g',compound)FROM rgmaplocation WHERE化合物LIKE'%g%'ORDER BY CHARINDEX('g',compound)UNION SELECT DISTINCT街道名,CHARINDEX('g',streetname)FROM rgmaplocation WHERE streetname LIKE '%g%'ORDER BY CHARINDEX('g',streetname) 它說 Msg 156,Level 15,State 1,Line 1 關鍵字'UNION'附近的語法不正確。 Msg 156,Level 15,State 1,Line 1 關鍵字'UNION'附近的語法不正確 – Jesper

+0

@Jesper我剛剛在SSMS中測試了我的初始3個SQL語句的建議。我沒有得到任何錯誤(除此之外,我沒有聲明變量@ ss',當然)。 –

+0

它不斷給這裏的錯誤。我已經按照此處所寫的內容添加了您的行。 – Jesper

4

事情是這樣的工會結果並通過charindex表達式進行排序。

;WITH C(Loc, Idx) AS 
(
    SELECT DISTINCT area, CHARINDEX('g', area) 
    FROM rgmaplocation 
    WHERE area LIKE '%g%' 
    UNION ALL 
    SELECT DISTINCT compound, CHARINDEX('g', compound) 
    FROM rgmaplocation 
    WHERE compound LIKE '%g%' 
    UNION ALL 
    SELECT DISTINCT streetname, CHARINDEX('g', streetname) 
    FROM rgmaplocation 
    WHERE streetname LIKE '%g%' 
) 
SELECT Loc, Idx 
FROM C 
ORDER BY Idx 
+1

或'UNION ALL',因爲無論如何這三個結果集可能都是不同的。 –

+0

@ypercube是的,工會都更好用。 –

相關問題