Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL:生成仅购买特定产品的用户列表_Mysql - Fatal编程技术网

MySQL:生成仅购买特定产品的用户列表

MySQL:生成仅购买特定产品的用户列表,mysql,Mysql,从电子商务数据库中,我需要识别购买了特定产品的用户,并且只识别该产品。已购买该产品和其他产品的用户除外 在订单表中,每一行对于所购买的产品都是唯一的 user_id | order_id | product_id 20 | 01 | 65 20 | 01 | 68 21 | 02 | 68 22 | 03 | 68 21 | 04 | 65 在上面的示例中,产品68是目标产品,用户22

从电子商务数据库中,我需要识别购买了特定产品的用户,并且只识别该产品。已购买该产品和其他产品的用户除外

在订单表中,每一行对于所购买的产品都是唯一的

user_id | order_id | product_id
20      | 01       | 65
20      | 01       | 68
21      | 02       | 68
22      | 03       | 68
21      | 04       | 65
在上面的示例中,产品68是目标产品,用户22将包括在列表中

包括其他产品在内的订单,即使其中包括68个,也会导致用户被排除在外。仅68的额外订单不会排除该用户

第二部分是将该用户id与第二个表中的电子邮件地址进行匹配,其中电子邮件地址和用户id是每个用户行的列。如何生成符合第一个条件的电子邮件地址列表


我可以通过PHP分多个步骤完成这项工作,但我想利用这个问题更好地了解如何利用SQL。

假设您的表是命名用户和订单,下面的查询将:

查找仅订购了单个产品的所有用户ID。 查找所有订购了product_id 68并且是步骤1结果成员的不同用户id。 将步骤2中的用户ID与users表连接以获取电子邮件地址。 设置:

create table users (
  user_id int primary key,
  email_address varchar(100)
);

create table orders (
  id int auto_increment primary key,
  user_id int,
  order_id int,
  product_id int
);

insert into users (user_id, email_address) values
  (20, 'twenty@email.com'),
  (21, 'twentyone@email.com'),
  (22, 'twentytwo@email.com');

insert into orders (user_id, order_id, product_id) values
  (20, 1, 65),
  (20, 1, 68),
  (21, 2, 68),
  (22, 3, 68),
  (21, 4, 65);
查询:

select email_address
from users
join (
    select distinct user_id
    from orders
    where product_id = 68 and user_id in (
        select user_id
        from orders
        group by user_id
        having count(distinct product_id) = 1
    )
) user_ids on user_ids.user_id = users.user_id;
结果:

twentytwo@email.com

试试看:

电子邮件的匹配只是用户id上两个表之间的简单连接。查找mysql连接,您会发现大量示例如果user22在两个或更多订单中使用相同的产品id,这是否匹配?您的需求是否特定于单个订单?如果客户在一个订单中只订购了一个产品,但在另一个订单中订购了一个或多个不同的产品,那么该客户是否应被排除在外?这有点不清楚。推论是可以的,但为什么不提及你正在思考的具体产品呢。此外,如能提供一些努力的证据,将不胜感激。请参阅:-另外,除非多个用户能够以某种方式共享单个订单的各个方面,否则您的模式是不规范的。我想说,您的问题与您最近的评论相矛盾。