gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:43:52 24 4
gpt4 key购买 nike

我在同一数据库中有两个表,一个名为“产品”,另一个名为“客户”,我需要获取 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

求助,谢谢

最佳答案

两者都应该有效:

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;

关于mysql - 如果它们具有相同的行数,如何基于 order_id 内部连接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31533556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com