嵌套选择查询更有效

时间:2019-04-23 15:44:52

标签: mysql

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_Code表

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(来自用户表),那么它应该检查code(来自user_code表),并且相同的代码应检查是否为其他{{1} }(来自user_code表),并且还应返回该user_id

例如。

user_id
从上表

,如果我得到 id username 679 sathis 680 ram 作为输入。我应该得到sathis作为输出结果。  因为ram的代码也显示了Sathis's

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

Ram

如何更有效地简化此查询,

1 个答案:

答案 0 :(得分:1)

为了提高性能,您可以避免使用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