如果它们具有相同的行数,则如何基于order_id连接内部表

时间:2015-07-21 08:07:46

标签: mysql sql-server database phpmyadmin

我在同一个数据库中有两个表,一个名为"产品"而另一个名为"客户",我需要获得customer.order_id,customer.name,customer.order_total,products.type但事情是,只有当有一个产品时才需要匹配结果客户,所以如果客户在另一个表上有多个产品,请忽略它并跳到下一个产品。

我有以下SQL内部加入我所需要的,但我不知道如何根据产品数量过滤结果(我甚至不想显示客户,如果他有不止一种产品。

例如

Customers Table         

order_id    name    order_total 
13445       John    650 
28837       Steve   300 
20039       Craig   200 
39487       Matt    475 


Products Table          

order_id    product_sku   product_price    product_type
13445       12345         650              Toys
28837       34434         175              Pool
28837       54453         125              Food
20039       43546         200              Toys
39487       34256         475              Food

这两张桌子需要的是:

order_id    name    order_total   product_type
13445       John    650           Toys
20039       Craig   200           Toys
39487       Matt    475           Food

我已尝试过类似的东西,但它让我得到了所有结果,包括拥有多种产品的客户

SELECT customer.order_id, customer.name, customer.order_total, products.type
FROM customer
INNER JOIN products
ON customer.order_id=products.order_id
WHERE customer.order_total != 0
ORDER BY customer.order_id DESC

请帮助,谢谢

2 个答案:

答案 0 :(得分:1)

两者都应该有效:

select c.*,p.product_type from Customers as c, Products as p where c.order_id = p.order_id and c.order_id in  
(select order_id from Products group by(order_id) having count(order_id) = 1);




select c.*, p.product_type from Products as p , Customers as c where  c.order_id = p.order_id  group by(p.order_id) having count(p.order_id) = 1;

答案 1 :(得分:0)

您正在寻找HAVING条款。与HAVING count(products.order_id) = 1

中一样

它可以让您对聚合事物制定条件。

http://www.w3schools.com/sql/sql_having.asp