2011-02-15 47 views
12

我有这个疑问:问题的限制和IN/ALL/ANY/SOME子查询

SELECT count(cp.CxID) as intSmokers 
FROM CustPrimarySmoking cp 
JOIN Customer c ON cp.CxID = c.CustomerID 
WHERE 
cp.CxID IN (SELECT CxID FROM CustPrimarySmoking WHERE CxID = cp.CxID LIMIT 1, 9999) 

的想法是,计数将基于嵌套查询的结果,其检索所有记录客户除第一条记录外。

不过,我得到这个错误,我认为这是相当终端:

1235 - 该版本的MySQL还不支持 'LIMIT & IN/ALL/ANY/SOME子查询'

有没有人知道这样做的任何其他方式?

感谢

+1

我亲爱的...`SELECT COUNT(cp.CxID)作为intSmokers FROM CustPrimarySmoking CP JOIN客户C对cp.CxID = c.CustomerID WHERE cp.CxID IN(SELECT CxID FROM CustPrimarySmoking WHERE CxID = cp.CxID)LIMIT 1,9999999` – ajreal 2011-02-15 13:21:48

+1

重写您的查询MySQL不支持子查询中的LIMIT。请参阅http://dev.mysql.com/doc/refman/5.0/en/subquery-restrictions.html – Nishant 2011-02-15 13:21:51

+0

AjReal,这将无法正常工作;你试图限制1的整数查询,它只检索一个结果(计数)。 – TheBounder 2011-02-15 13:25:29

回答

32

这是你需要如何继续。看看我已经制定的例子。

mysql> select * from test; 
+------+-------+ 
| id | name | 
+------+-------+ 
| 1 | name1 | 
| 2 | name2 | 
| 3 | name3 | 
| 4 | name4 | 
+------+-------+ 
4 rows in set (0.00 sec) 

mysql> select * from test1; 
+------+------+--------+ 
| id | tid | name2 | 
+------+------+--------+ 
| 1 | 2 | name11 | 
| 2 | 3 | name12 | 
| 3 | 4 | name13 | 
+------+------+--------+ 
3 rows in set (0.00 sec) 

mysql> select 
    -> t1.name 
    -> from 
    -> test t1 
    -> join 
    -> test1 t2 on t2.tid = t1.id 
    -> join 
    -> (select id from test where id <4 limit 3) as tempt on tempt.id = t1.id; 
+-------+ 
| name | 
+-------+ 
| name2 | 
| name3 | 
+-------+ 
2 rows in set (0.00 sec) 

希望这会有所帮助。

1

你不需要使用子查询检索所有的记录,只排除第一种:

SELECT count(cp.CxID) as intSmokers FROM CustPrimarySmoking cp JOIN Customer c ON cp.CxID = c.CustomerID WHERE cp.CxID > (SELECT cxID FROM CustPrimarySmoking ORDER BY cxID LIMIT 1)

假设cxid是数字

0

这种限制是一个痛苦,如果你想要得到的东西,如“前N行的每一组” 。但在你的情况下,即使可能,我也不会使用该功能。你试图做的是统计除了每行之外的所有行,CxID。您所需要的仅仅是减去不同CustomerID的数量,即count(DISTINCT cp.CxID)。因此,最终的查询应该是简单的:

SELECT count(cp.CxID) - count(DISTINCT cp.CxID) as intSmokers 
FROM CustPrimarySmoking cp