SQL 查询 - 如何在 WHERE 子句中放置条件
SQL query - how to put conditions in WHERE clause
我是 SQL 的新手,我想知道是否可以在 WHERE
子句之后添加一个条件。更具体地说,我试图在我的数据库中找出 "which item have been sold to two people"。
我已经成功地连接了所有卖给人们的物品,并且想要一个只给出卖给两个人的物品的条件。我试过在 WHERE
子句中使用 COUNT(customer_id)
但它给出了 "aggregates not allowed in WHERE clause"。
编辑:
数据库 表是:
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;
谢谢大家!
您需要使用 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
继续;
您应该学习如何使用正确的 join
语法和 table 别名:
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
.
我是 SQL 的新手,我想知道是否可以在 WHERE
子句之后添加一个条件。更具体地说,我试图在我的数据库中找出 "which item have been sold to two people"。
我已经成功地连接了所有卖给人们的物品,并且想要一个只给出卖给两个人的物品的条件。我试过在 WHERE
子句中使用 COUNT(customer_id)
但它给出了 "aggregates not allowed in WHERE clause"。
编辑:
数据库 表是:
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;
谢谢大家!
您需要使用 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
继续;
您应该学习如何使用正确的 join
语法和 table 别名:
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
.