gpt4 book ai didi

MySQL:查询行的子集

转载 作者:太空宇宙 更新时间:2023-11-03 11:59:10 26 4
gpt4 key购买 nike

给出下表:

表:USER_ASSETS

USER_ID | ASSET_ID
-------------------
1 | 1
-------------------
1 | 2
-------------------
1 | 3
-------------------
2 | 2
-------------------
2 | 3
-------------------

如果我搜索 ASSET_ID 等于 1 和 2 的 USER_ID,它应该返回 USER_ID 1 作为 USER_ID 1 有 ASSET_ID 的 1 和 2。

如果我传递 ASSET_ID = 1 and 2 and 4,它应该返回 0 行,因为没有 USER_ID 具有 ASSET_ID 1、2 和 4。

如果我传递 ASSET_ID 2 和 3,它应该返回 USER_ID 1 和 2,因为这两个 USER_ID 都有 ASSET_ID 2 和 3。

我现在被卡住了,因为我找不到我想要的结果的正确查询。

我试过这个:

SELECT DISTINCT ID FROM USER_ASSETS WHERE ASSET_ID IN (1, 2);

但结果是错误的,因为它同时返回了 USER_ID 1 和 2。

我也试过:

SELECT DISTINCT ID FROM USER_ASSETS WHERE ASSET_ID = 1 AND ASSET_ID = 2

但这总是返回 0 行,因为 WHERE 子句一次只对一行执行。

最佳答案

你可以尝试这样的事情:

select user_id
from user_assets
where asset_id = 1 or asset_id = 2 ...
group by user_id
having count(distinct asset_id) = (number of assets you are looking for)

demo here显示您需要的输出。

如果 (user_id, asset_id) 是一个唯一键,那么 distinct 就不是必需的

关于MySQL:查询行的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30430579/

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