子查询上的子查询

时间:2013-06-14 09:26:20

标签: sql database ms-access subquery

我正在尝试创建一个select语句

我需要从一个表中收集一条记录,该记录等于另一个表中使用的相同代码。

更好的是,客户从下拉列表中选择该城市的城市和类别。 当客户端点击下一步时,将显示该城市中符合该类别的各个位置。 但我无法弄清楚我哪里出错了。

现在,当客户选择一个城市时,每个城市都有两条记录,一个正确的城市代码和一个以'bx'作为第一个字母的邮政编码

在我的第一个查询中,为了消除重复,我说

select c.[Description] from city c 
where c.Provincecode like 'EC' and 
      c.citycode in (select c.citycode from City c 
                     where SUBSTRING(c.citycode,0,3) not like 'bx')

给了我一个城市名称。

但现在,如果客户选择了,例如,只有现金的地方可以看到, 结果中只应显示一条记录

但尽可能地尝试,我无法获得正确的语法

我试过了:

select c.[Description] from city c 
where c.Provincecode like 'EC' and 
      c.citycode in (select c.citycode from City c 
                     where SUBSTRING(c.citycode,0,3) not like 'bx') 
      and exists (select * from Customers cu 
                  where cu.Category like 'SC' and cu.Province like 'EC')

但是这会带来比预期更多的结果

这是使用访问数据库完成的,但我使用SQL进行编码,我将其重新编写为访问权限。这不是问题

所以,如果有人可以提供SQL答案,我可以从那里做其余的

我不确定我是否应该加入。 我确实试过了

select * from 
(select c.[Description] from city c 
 where c.Provincecode like 'EC' and 
       c.citycode in (select c.citycode from City c 
                      where SUBSTRING(c.citycode,0,3) not like 'bx')) x 
join Customers on  province=city.provincecode where Category like 'SC'

但是我发现错误的多部分标识符无法绑定


修改

这是新查询

select * 
from 
    (
        select c.* 
        from city c 
        where c.Provincecode like 'EC' 
            and c.citycode in
                (
                    select c.citycode 
                    from City c 
                    where SUBSTRING(c.citycode,0,3) not like 'bx'
                )
    ) x 
    join 
    Customers  
        on  province=x.Provincecode 
where Category like 'SC'

返回的是 enter image description here

正如您所看到的,有太多的结果让C Strydom成为客户,但所有城市都在那里

对于这个特定的例子,只显示一条记录,第二条记录 enter image description here

2 个答案:

答案 0 :(得分:0)

虽然我不喜欢使用SELECT *,但你知道更多你想要的实际列,我把它留给你。查询应该很简单,因为您主要查看特定省代码的“城市”表,但不以“bx”开头。只需在你的where子句中有这个...你可以测试关于记录的多个事情而不必在其他一些标准上加入自己。完成后,只需简单地连接到您要限制的类别的客户表。

select *
   from 
      city c 
         JOIN Customers CU
            on c.ProvinceCode = CU.Province
           AND CU.Category like 'SC'
   where 
          c.ProvinceCode like 'EC' 
      and NOT substr( c.CityCode,0,3 ) = 'bx'

现在,您的每个客户的多条记录问题。如果您加入的是省级代码到客户表,您将获得笛卡尔结果...但如果您加入到客户的省代码和城市,您将只获得匹配的单个代码...但我们没有客户表详细信息来确认列关系。

答案 1 :(得分:0)

问题是JOIN不完整(详见问题评论)。有效的查询是

select * 
from 
    (
        select c.* 
        from city c 
        where c.Provincecode like 'EC' 
            and c.citycode in
                (
                    select c.citycode 
                    from City c 
                    where SUBSTRING(c.citycode,0,3) not like 'bx'
                )
    ) x 
    INNER JOIN 
    Customers 
        ON Customers.province=x.Provincecode 
            AND Customers.city=x.Citycode 
where Category like 'SC'