我是SQL的新手,我想知道是否可以在WHERE
子句之后添加条件。更具体地说,我试图找出"哪个项目已经卖给了两个人"在我的数据库中。
我设法将所有已售出的商品连接到人们,并希望条件只提供已售出给两个人的商品。我尝试在COUNT(customer_id)
子句中使用WHERE
,但它在WHERE子句"中提供了#34;不允许的聚合。
修改
数据库表格为:
books((book_id), title, author_id, subject_id)
publishers((publisher_id), name, address)
authors((author_id), last_name, first_name)
stock((isbn), cost, retail_price, stock)
shipments((shipment_id), customer_id, isbn, ship_date)
customers((customer_id), last_name, first_name)
editions((isbn), book_id, edition, publisher_id, publication_date)
subjects((subject_id), subject, location)
我当前的查询是:
SELECT title, first_name, last_name
FROM books, shipments, customers, editions
WHERE books.book_id = editions.book_id
AND editions.isbn = shipments.isbn
AND shipments.customer_id = customers.customer_id
AND COUNT(customers.customer_id) = 2;
谢谢大家!
答案 0 :(得分:2)
您需要使用HAVING
子句,如下所示:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator val
UE;
答案 1 :(得分:0)
您应该学习如何使用正确的join
语法和表别名:
SELECT b.title, c.first_name, c.last_name
FROM books b join
editions e
on b.book_id = e.book_id join
shipments s
on e.isbn = s.isbn join
customers c
on s.customer_id = c.customer_id
GROUP BY title, first_name, last_name
HAVING COUNT(customers.customer_id) = 2;
您的问题的答案是HAVING
子句以及GROUP BY
。