gpt4 book ai didi

mysql 查询为用户和相关表获取不同的值

转载 作者:行者123 更新时间:2023-11-30 00:01:26 26 4
gpt4 key购买 nike

我有一个名为“games”的表。在此表中有几个字段。相关字段是 用户1 用户2 第1轮 第二轮 第三轮

字段 user1 和 user2 是整数/id,当然是从表“user”中获取的(以 id 和 name 作为字段)。

字段 第1轮 第二轮 第三轮是从表“问题”中获取的整数/ID。

现在我需要的是创建一个 sql 查询,该查询将从表“问题”中获取 ID,但只获取用户尚未使用的那些问题 ID。

我的想法是做类似的事情(当正在玩的用户的 ID 等于 1 AND 2 时):

select from questions where id NOT IN (select round1 from questions where (user1 = 1 OR user1 = 2 OR user2 = 1 OR user2 = 2)  )

我不确定这个查询是否真的看起来不错并且是否经过优化。然而,它还没有完成。实际上,我还需要再添加 2 个 WHERE 标准,这些条件类似于上面的条件,其中 round1 被 round2 和 round3 替换。所以最终它可能看起来像:

select from questions 
where id NOT IN (select round1 from questions where
(user1 = 1 OR user1 = 2 OR user2 = 1 OR user2 = 2) )
and id NOT IN (select round2 from questions where
(user1 = 1 OR user1 = 2 OR user2 = 1 OR user2 = 2) )
and id NOT IN (select round3 from questions where
(user1 = 1 OR user1 = 2 OR user2 = 1 OR user2 = 2) )

此外,我可能需要在 round1/round2/round3 之前添加“distinct”。

那么,您认为有更好的方法吗?提前致谢。

最佳答案

您可以使用UNION尝试如下所示的操作

select * from questions 
where id NOT IN (
select distinct round1
from questions
where user1 in (1,2) OR user2 in (1,2)

UNION

select distinct round2
from questions
where user1 in (1,2) OR user2 in (1,2)

UNION

select distinct round3
from questions
where user1 in (1,2) OR user2 in (1,2)
)

关于mysql 查询为用户和相关表获取不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25002793/

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