如果它们具有相同的行数,如何基于 order_id 内部连接表
how to inner join tables based on order_id if they have the same number of rows
我在同一个数据库中有两个table,一个叫"products",另一个叫"customers",我需要得到customer.order_id,customer.name, customer.order_total, products.type 但问题是只有当这个客户有一个产品时我才需要匹配结果,所以如果客户有多个产品在另一个 table忽略它并跳到下一个。
我有以下 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
我需要从这两个 table 中得到的是:
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
请帮忙,谢谢
两者都应该有效:
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;
我在同一个数据库中有两个table,一个叫"products",另一个叫"customers",我需要得到customer.order_id,customer.name, customer.order_total, products.type 但问题是只有当这个客户有一个产品时我才需要匹配结果,所以如果客户有多个产品在另一个 table忽略它并跳到下一个。
我有以下 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
我需要从这两个 table 中得到的是:
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
请帮忙,谢谢
两者都应该有效:
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;