如何从订阅列表中获取仅订阅英语频道的用户
Posted
技术标签:
【中文标题】如何从订阅列表中获取仅订阅英语频道的用户【英文标题】:From a subscribed list how get users who only subscribed to English channels 【发布时间】:2019-07-26 16:46:09 【问题描述】:我的表格有用户订阅英语和印地语频道的记录,我只想要订阅英语的用户
+--------+------+------+------+
| 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 |
+--------+------+------+------+
【问题讨论】:
为什么结果表中没有id 1和4?他们还订阅了英语 你可以做select * from YOUR_TABLE_NAME where Subscribedto='English';
我想你的意思是“只订阅英语”
【参考方案1】:
假设subscribedto
列中没有空值,您可以使用 NOT EXISTS:
select t.*
from tablename t
where not exists (
select 1 from tablename
where userid = t.userid and subscribedto <> 'English'
)
请参阅demo。 结果:
| 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'
)
结果是一样的,但这个版本可能会更高效。
【讨论】:
【参考方案2】:DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,user_id INT NOT NULL
,subscribed_to VARCHAR(12) NOT NULL
,UNIQUE KEY(user_id,subscribed_to)
);
INSERT INTO my_table VALUES
(1,1,'English'),
(2,2,'English'),
(3,1,'Hindi'),
(4,3,'English'),
(5,3,'Hindi'),
(6,4,'English');
SELECT DISTINCT x.*
FROM my_table x
LEFT
JOIN my_table y
ON y.user_id = x.user_id
AND y.subscribed_to <> x.subscribed_to
WHERE x.subscribed_to = 'English'
AND y.id IS NULL;
+----+---------+---------------+
| id | user_id | subscribed_to |
+----+---------+---------------+
| 2 | 2 | English |
| 6 | 4 | English |
+----+---------+---------------+
【讨论】:
【参考方案3】:分析功能将在单表扫描中执行此操作,无需昂贵的连接。它将在 Hive 中工作:
SELECT id, userid, subscribedto
FROM
(
SELECT id, userid, subscribedto,
max(case when subscribedto != 'English' then true else false end) over(partition by userid ) subscribed_not_english
FROM my_table s
)s
WHERE NOT subscribed_not_english
【讨论】:
以上是关于如何从订阅列表中获取仅订阅英语频道的用户的主要内容,如果未能解决你的问题,请参考以下文章