如何在mysql中不使用子查询的情况下查找某些特定记录

Art*_*ngh 5 mysql join

我的数据库中有 2 个表。两者都有大约 100M 记录。我的第一个表 uph 包含订单的详细信息,另一个 urs 包含客户的详细信息。它们的结构是:

mysql> desc uph;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| uid        | int(11)      | NO   |     | NULL    |                |
| order_from | varchar(255) | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)

mysql> desc usr;
+---------+----------+------+-----+---------+----------------+
| Field   | Type     | Null | Key | Default | Extra          |
+---------+----------+------+-----+---------+----------------+
| uid     | int(11)  | NO   | PRI | NULL    | auto_increment |
| profile | char(10) | NO   |     | NULL    |                |
+---------+----------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)

两个表都有这样的数据:

mysql> select * from usr;
+-----+----------+
| uid | profile  |
+-----+----------+
|   1 | in-store |
|   2 | ecom     |
|   3 | ecom     |
|   4 | in-store |
|   5 | ecom     |
+-----+----------+
4 rows in set (0.00 sec)

mysql> select * from uph;
+----+-----+------------+
| id | uid | order_from |
+----+-----+------------+
|  1 |   1 | in-store   |
|  2 |   2 | ecom       |
|  3 |   1 | ecom       |
|  4 |   4 | in-store   |
+----+-----+------------+
4 rows in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)

现在,我想找到那些配置文件为“ecom”的用户,如果他们已经购买过,那么 order_from 应该只是“ecom”。如果没有购买任何只有个人资料的东西,仍将被视为“ecom”用户。

如果任何用户同时从 ecom 和 In-store 购买,这些将从结果中排除。这意味着用户不应与 In-store 有任何关系。

因此,在查询的输出中,我们将得到如下结果:

+----+
| uid |
+-----+
|  2  |
|  3  |
|  5  |
+-----+
Run Code Online (Sandbox Code Playgroud)

由于两个表都包含大量数据,因此我仅限于用户子查询。请建议如何在不使用子查询的情况下做到这一点。

M K*_*aid 2

您可以进行联接并检查聚合结果是否符合您的条件

select u.uid, u.profile
from usr u
left join uph p on u.uid = p.uid
where u.profile = 'ecom'
group by u.uid, u.profile
having sum(case when p.order_from = 'in-store' then 1 else 0 end) = 0
Run Code Online (Sandbox Code Playgroud)