首页 > 解决方案 > 如何从订阅列表中获取仅订阅英语频道的用户

问题描述

我的表格包含订阅英语和印地语频道的用户记录,我只想要订阅英语的用户

+--------+------+------+------+
| id | userid | Subscribedto |   
+--------+------+------+------+
|  1 |   1     |   English   |
|  2 |   2     |   English   |
|  3 |   1     |   Hindi     |
|  4 |   3     |   English   |
|  4 |   3     |   Hindi     |
|  5 |   4     |   English   |
+--------+------+------+------+

所以结果将是

+--------+------+------+------+
| id | userid | Subscribedto |   
+--------+------+------+------+
|  2 |   2     |   English   |
|  5 |   4     |   English   |
+--------+------+------+------+

标签: mysqlsqlhivehiveql

解决方案


假设列中没有空值,subscribedto您可以使用 NOT EXISTS:

select t.*
from tablename t
where not exists (
  select 1 from tablename
  where userid = t.userid and subscribedto <> 'English'
)

请参阅演示
结果:

| id  | userid | subscribedto |
| --- | ------ | ------------ |
| 2   | 2      | English      |
| 5   | 4      | English      |

您还可以在 where 子句中添加条件subscribedto = 'English'

select t.*
from tablename t
where subscribedto = 'English' and not exists (
  select 1 from tablename
  where userid = t.userid and subscribedto <> 'English'
)

结果是一样的,但是这个版本可能会稍微高效一些。


推荐阅读