从具有多行的嵌套查询中进行选择

时间:2013-04-22 20:12:29

标签: php mysql nested-queries

下面的

是给定的表格。

----------------------------------
| area   |  country  |   date     |  
----------------------------------
| a1     |     c1    | 13-01-2013 | 
----------------------------------
| a2     |     c2    | 06-01-2013 | 
----------------------------------
| a3     |     c1    | 12-01-2013 | 
----------------------------------
| a4     |     c2    | 10-01-2013 | 
----------------------------------
| a5     |     c3    | 13-01-2013 | 
----------------------------------
| a1     |     c1    | 13-01-2013 | 
----------------------------------
| a2     |     c2    | 06-01-2013 | 
----------------------------------
| a3     |     c1    | 12-01-2013 | 
----------------------------------
| a4     |     c2    | 10-01-2013 | 
----------------------------------
| a5     |     c3    | 13-01-2013 | 

我希望我的查询可以执行以下操作。

“显示在两个给定日期之间区域出现多次的国家/地区的名称。”

我尝试了以下查询,但它给了我一个错误。 >  #1242 - 子查询返回超过1行

SELECT country
FROM table
WHERE area = (
SELECT area
FROM table
WHERE dateandtime > ' 13-01-2013'
AND dateandtime < '20-01-2013'
GROUP BY area
HAVING count(DISTINCT date) > 1 );

3 个答案:

答案 0 :(得分:1)

要将值与值列表进行比较,您需要使用IN。我还做了一些修改来修复你的语法。

SELECT country
FROM table
WHERE area IN (
SELECT area
FROM table
WHERE dateandtime > ' 13-01-2013'
AND dateandtime < '20-01-2013'
GROUP BY area, country, `date`
HAVING count(date) > 1 )
);

我相信查询也可以简化为:

SELECT country
FROM table
GROUP BY area, country, `date`
HAVING count(date) > 1
AND dateandtime BETWEEN '14-01-2013' AND '19-01-2013'
);

答案 1 :(得分:0)

如果您想要一个国家/地区,请不要选择某个区域:

SELECT DISTINCT country
FROM (
   SELECT country
   FROM table
   WHERE dateandtime > ' 13-01-2013'
   AND dateandtime < '20-01-2013'
   GROUP BY area
   HAVING count(DISTINCT date) > 1
) areas;

答案 2 :(得分:0)

你可能正在寻找这个

    SELECT country
    FROM table1

    WHERE date between ' 13-01-2013' AND  '20-01-2013'

    GROUP BY country
    HAVING count(date) > 1 ;

DEMO HERE