我试图编写一个在sql中使用count的查询。我想写的查询是。
Find users that reviewed at least 2 restaurants.
以下是我正在使用的表格:
explain is_a_restaurant;
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| business_id | int(11) | NO | PRI | NULL | |
| cuisine_type | varchar(20) | YES | | NULL | |
| total_seats | int(11) | YES | | 1 | |
+--------------+-------------+------+-----+---------+-------+
explain reviews;
+-------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------+------+-----+---------+-------+
| business_id | int(11) | NO | PRI | NULL | |
| user_id | int(11) | NO | PRI | NULL | |
| review_id | int(11) | NO | PRI | NULL | |
| review_date | date | YES | | NULL | |
| star_rating | int(1) | YES | | 1 | |
+-------------+---------+------+-----+---------+-------+
explain users;
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| user_id | int(11) | NO | PRI | NULL | |
| name | varchar(50) | YES | | NULL | |
| user_since | date | YES | | NULL | |
这是我尝试过的(香港专业教育学院尝试的远不止这个,但是还有一个):
SELECT reviews.user_id FROM reviews JOIN is_a_restaurant ON
(reviews.business_id = is_a_restaurant) WHERE (count(*).is_a_restaurant > 1)
GROUP BY reviews.user_id ASC;
这是我得到的错误
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use
near '.is_a_restaurant > 1) GROUP BY reviews.user_id ASC' at line 1
答案 0 :(得分:1)
您需要HAVING
子句。
SELECT reviews.user_id
FROM reviews
JOIN is_a_restaurant ON (reviews.business_id = is_a_restaurant.business_id)
GROUP BY reviews.user_id ASC
HAVING count(*) > 1
答案 1 :(得分:1)
我不是一个MySQL人,所以我的语法可能有点过,但你可能想要使用HAVING子句。
SELECT reviews.user_id
FROM reviews
JOIN is_a_restaurant ON reviews.business_id = is_a_restaurant.business_id
GROUP BY reviews.user_id ASC
HAVING COUNT(*) > 1;
HAVING子句类似于WHERE子句,但用于聚合值(在本例中为COUNT)。
您还错过了JOIN表达式中is_a_restaurant的列名。
答案 2 :(得分:0)
count()是一个聚合函数。 SQL聚合函数是返回单个值的函数,它是根据列中的值计算的。您不能将where子句与聚合函数一起使用。相反,您必须使用having子句。 以下是最常用的聚合函数。
所以,使用而不是在哪里。 保重,祝你好运.... !!