繁体   English   中英

SQL查询-如何在WHERE子句中放置条件

[英]SQL query - how to put conditions in WHERE clause

我是SQL的新手,我想知道是否可以在WHERE子句后放置一个条件。 更具体地说,我试图在数据库中找出“哪些商品已卖给两个人”。

我设法将已经卖给人们的所有物品联系起来,并希望有一个条件,仅给出已卖给两个人的物品。 我试过在WHERE子句中使用COUNT(customer_id) ,但它给出了“ WHERE子句中不允许的聚合”。

编辑:

数据库表是:

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

ue;

您应该学习如何使用正确的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM