在选择列表MSSQL查询

时间:2018-06-20 09:05:29

标签: sql-server

我有一个包含此列的表

  Name |  Country | Place | ZIP | Street

我需要像这样过滤记录:

SELECT Name, Country, Place, ZIP, Street FROM Addresses
WHERE Active <> 0 AND
Country IN ('FR', 'DE', 'PL', 'CH')

这是可行的,但现在我想将国家/地区和邮政编码过滤到特定国家/地区。

我试图做这样的事情:

SELECT Name, Country, Place, ZIP, Street FROM Addresses
WHERE Active <> 0 and
Country IN (SELECT Country FROM Addresses WHERE Country = 'FR' AND ZIP BETWEEN 'xxxx' AND 'xxxx')

不幸的是,我遇到一个错误:

  

如果选择列表中只能指定一个表达式   子查询未使用EXISTS启动。

(德语翻译)

我为什么要这样,因为此查询转到php。用户可以选择将哪个国家和哪个邮政编码过滤到该指定国家。

2 个答案:

答案 0 :(得分:0)

您可以使用子选择来过滤查询的数据(根据用户指定)。

SELECT * FROM (
    SELECT Name, Country, Place, ZIP, Street FROM Addresses
    WHERE Active <> 0 AND
    Country IN ('FR', 'DE', 'PL', 'CH')
) all_countries WHERE Country = 'FR' AND ZIP BETWEEN 'xxxx' AND 'xxxx'

要使用多个过滤器,可以使用以下内容:

SELECT * FROM (
    SELECT Name, Country, Place, ZIP, Street FROM Addresses
    WHERE Active <> 0 AND
    Country IN ('FR', 'DE', 'PL', 'CH')
) all_countries 
WHERE (Country = 'FR' AND ZIP BETWEEN 'xxxx' AND 'xxxx') OR
      (Country = 'DE' AND ZIP BETWEEN 'xxxx' AND 'xxxx')

答案 1 :(得分:0)

假设您有一个提供结果的查询,并且需要添加更多过滤器,则可以添加到查询的WHERE子句中。

在您的情况下,原始查询为

SELECT Name, Country, Place, ZIP, Street FROM Addresses
WHERE Active <> 0 AND
Country IN ('FR', 'DE', 'PL', 'CH')

,您想添加WHERE Country = 'FR' AND ZIP BETWEEN 'xxxx' AND 'xxxx'

因此,如果您想进一步过滤所有记录,则只需在下面的where子句中添加

SELECT Name, Country, Place, ZIP, Street FROM Addresses
WHERE Active <> 0 AND
Country IN ('FR', 'DE', 'PL', 'CH')
AND 
Country = 'FR' AND ZIP BETWEEN 'xxxx' AND 'xxxx'

或者如果您只是想过滤出法国的邮政编码,则您的查询应该是

SELECT Name, Country, Place, ZIP, Street FROM Addresses
WHERE Active <> 0 AND
Country IN ('FR', 'DE', 'PL', 'CH')
OR 
(
  Country = 'FR' AND ZIP BETWEEN 'xxxx' AND 'xxxx'
)

注意,我使用OR而不是ADD并在括号内分离出了多余的条件,以表明它们属于同一段