涉及多个联接的子查询

时间:2012-05-17 19:54:07

标签: sql

仍在尝试习惯编写查询,但我遇到了问题。

Select count(region)
where (regionTable.A=1) in
(
select jxn.id, count(jxn.id) as counts, regionTable.A
from jxn inner join
               V on jxn.id = V.id inner join
               regionTable on v.regionID = regionTable.regionID
group by jxn.id, regionTable.A
)

内部查询在一列中给出一个ID号,它们在表中出现的次数,然后是一个位属性,如果它们在区域A中。外部查询有效,但我得到的错误是{{1} }。在内部查询中,我想了解其中有多少是在区域A

4 个答案:

答案 0 :(得分:1)

您必须在查询之前指定表名

  Select count(region)
    from table
    where (regionTable.A=1) in

你必须选择其中一个。

where regionTable.A = 1 

where regionTable.A in (..)

答案 1 :(得分:1)

您的查询有几个语法错误。根据您的意见,我认为不需要子查询,您想要这个:

select jxn.id, count(jxn.id) as counts, regionTable.A
from jxn inner join
               V on jxn.id = V.id inner join
               regionTable on v.regionID = regionTable.regionID
where regionTable.A = 1
group by jxn.id, regionTable.A

可以进一步简化为:

select jxn.id, count(jxn.id) as counts
     , 1 as A                             --- you can even omit this line
from jxn inner join
               V on jxn.id = V.id inner join
               regionTable on v.regionID = regionTable.regionID
where regionTable.A = 1
group by jxn.id

答案 2 :(得分:0)

由于这一行,您收到错误:

where (regionTable.A=1)

您不能在where in子句中指定条件,它应该只是列名

答案 3 :(得分:0)

这样的事情可能就是你想要的:

SELECT COUNT(*)
FROM 
    (
        select jxn.id, count(jxn.id) as counts, regionTable.A 
        from 
            jxn inner join
            V on jxn.id = V.id inner join
            regionTable on v.regionID = regionTable.regionID 
        group by jxn.id, regionTable.A
    ) sq
WHERE sq.a = 1