gpt4 book ai didi

mysql - 嵌套选择查询更高效

转载 作者:行者123 更新时间:2023-11-29 07:22:02 25 4
gpt4 key购买 nike

useruser_code 表具有一对多关系。请找到下表结构。

用户表

 id email   username    date
679 test@test.com sathis 4/20/2019 9:04
679 test@test.com sathis 4/20/2019 9:04
679 test@test.com sathis 4/20/2019 9:04
679 test@test.com sathis 4/20/2019 9:04
679 test@test.com sathis 4/20/2019 9:04
679 test@test.com sathis 4/20/2019 9:04
679 test@test.com sathis 4/20/2019 9:04
679 test@test.com sathis 4/20/2019 9:04
680 test@test.com ram 4/20/2019 9:04
680 test@test.com ram 4/20/2019 9:04
680 test@test.com ram 4/20/2019 9:04
681 test@test.com Steve 4/20/2019 9:04
681 test@test.com Steve 4/20/2019 9:04
681 test@test.com Steve 4/20/2019 9:04
681 test@test.com Steve 4/20/2019 9:04
681 test@test.com Steve 4/20/2019 9:04

用户代码表

user_id code
679 J039
679 J080
679 J320
679 J54L
679 K31P
679 L05C
679 T030
679 V150
680 J039
680 J080
680 J320
681 ABC12
681 CD123
681 opo123
681 qw123
681 ieu12

如果我给 username(来自 user 表),那么它应该检查 code(来自 user_code 表)并且相同的代码应该检查它是否出现在一些其他 user_id(来自 user_code 表)并且应该返回那个 user_id

例如。

  id    username
679 sathis
680 ram

从上表中,如果我得到 sathis 作为输入。我应该得到 ram 作为输出结果。 因为 Sathis 的 代码也为 Ram 提供。

请在下面找到我的sql嵌套查询

select id,username from users
where
id in (
select user_id from user_code
where
code in (
select code from user_code
where user_id = ( select id from user where username = 'sathis')))

我怎样才能更有效地简化这个查询,

最佳答案

为了提高性能,您可以避免使用 IN 子句并在子查询上使用内部联接

select id, username 
from users
inner join (
select distinct user_id
from User_Code
inner join (
select code
from User_Code
inner join User ON User_Code.user_id = user.id
where username = 'sathis'
) t on t.code = User_Code.code
) t2 on t2.user_id = users.id

关于mysql - 嵌套选择查询更高效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55814935/

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