选择最小id


Selecting min id

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

这里我使用

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

,但它给了我一个错误。我知道我可以做同样的

SELECT cat_id FROM member_product_cat WHERE cat_parent_id=(SELECTMin (cat_parent_id) from member_product_cat where cat_parent_id !=0)限制1

但是我的第一种方法有什么问题?我们不是有为这个条款吗?

的问候Himanshu Sharma

HAVING子句被添加到SQL中,因为WHERE关键字不能用于聚合函数。所以你根本不需要在那里。

尝试:

<>之前WHERE cat_parent_id <> 0 WHERE cat_parent_id=(SELECT min(cat_parent_id) FROM member_product_cat) LIMIT 1

我认为你所需要的只是

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

当使用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.