如何组合同一个表中的三个“select distinct”

时间:2011-10-16 07:11:04

标签: sql database sql-server-2005

对于搜索功能,我想返回三种类型的结果,所以我查询了三次。将查询加入或联合到一个可能会更好,但是如何...

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 个答案:

答案 0 :(得分: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 :(得分:3)

Mikael Eriksson's solution如果您不介意将区域,化合物和街道名称混淆,那就很好。如果你想把它们分开,你可以去

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

答案 2 :(得分:1)

使用UNION,正如您所说的那样:

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