选择min id

时间:2011-12-04 17:11:20

标签: php mysql

我有一个简单的关系,其中类别和子类别由parent_id区分,类别具有parent_id 0,子类别具有category_id作为其parent_id。我想要做的是选择第一个类别的第一个子类别。

为此我正在使用

  

SELECT cat_id FROM member_product_cat WHERE cat_parent_id!= 0 HAVING   cat_parent_id = min(cat_parent_id)LIMIT 1

但它给了我一个错误。我知道我可以通过

做同样的事情
  

SELECT cat_id FROM member_product_cat WHERE cat_parent_id =(选择   来自member_product_cat的min(cat_parent_id),其中cat_parent_id!= 0)   限制1

但是我的第一种方法出了什么问题?不是因为我们有条款吗?。

此致 Himanshu Sharma

4 个答案:

答案 0 :(得分:1)

HAVING子句已添加到SQL,因为WHERE关键字不能与聚合函数一起使用。所以你根本不需要那里。

答案 1 :(得分:0)

尝试:

SELECT cat_id FROM member_product_cat WHERE cat_parent_id <> 0 where cat_parent_id=(SELECT min(cat_parent_id) from member_product_cat) LIMIT 1

答案 2 :(得分:0)

我认为你所需要的只是

SELECT cat_id FROM member_product_cat 
WHERE cat_parent_id !=0 
ORDER BY cat_parent_id, cat_id LIMIT 1

答案 3 :(得分:0)

在使用having而不使用group by时,即使使用了聚合函数,having子句在某种程度上也像where子句。

快速浏览文档:

http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-columns.html

引用:

Standard SQL does not permit the HAVING clause to name any column not found in the GROUP BY clause unless it is enclosed in an aggregate function. MySQL permits the use of such columns to simplify calculations. This extension assumes that the nongrouped columns will have the same group-wise values. Otherwise, the result is indeterminate.

我希望这会有所帮助

相关问题