2来自同一个表的嵌套查询?

gev0vcfq  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(359)

所以我有三张table
用户表

UserId User

语言表

LanguageId Language Fluency

用户语言表

UserLanguageId UserId LanguageId

基本上我需要的是一个查询,其中prilang是fluency='primary',seclang是fluency='secondary',看起来像这样

+------------+-----------------+-----------+
| User       | PriLang         | SecLang   |
+------------+-----------------+-----------+
| Jimbo      | English         | Spanish   |
+------------+-----------------+-----------+
| Norm       | French          | Spanish   |
+------------+-----------------+-----------+
| Kathy      | Japanese        | Italian   |
+------------+-----------------+-----------+
o7jaxewo

o7jaxewo1#

在我看来,最直接的方法包括两个到user\u languages表的连接,以及每个到langauges表的连接。

select  usr.User, lg1.Language PriLang, lg2.Language SecLang 
from users usr
 left join user_languages ul1
  on ul1.userId = usr.userId
   and ul1.Fluency='Primary'
 left join user_languages ul2
  on ul2.userId = usr.userId
   and ul2.Fluency='Secondary'
 left join languages lg1
  on lg1.languageId = ul1.languageId
 left join languages lg2
  on lg2.languageId = ul2.languageId
pexxcrt2

pexxcrt22#

一个选项使用条件聚合:

select 
    u.user,
    max(case when l.fluency = 'Primary' then l.language end) as pri_lang,
    max(case when l.fluency = 'Secondary' then l.language end) as sec_lang
from users u 
left join user_languages ul on ul.user_id = u.user_id
left join languages l on l.language_id = ul.language_id
group by u.user_id, u.user
v09wglhw

v09wglhw3#

也许像这样的事情取决于你的设置;这将使用子查询关闭:

SELECT u.User,
       (SELECT lt.Language
        FROM Language_table lt
            JOIN UserLanguage_table ult ON lt.LanguageId = ult.LanguageId 
            JOIN User_table u ON ult.UserId = u.UserId
        WHERE lt.Language_Fluency = 'primary'
            AND ult.UserId = u.UserId
            AND lt.LanguageId = ult.LanguageId) AS primary_lang,
       (SELECT lt.Language
        FROM Language_table lt
            JOIN UserLanguage_table ult ON lt.LanguageId = ult.LanguageId 
            JOIN User_table u ON ult.UserId = u.UserId
        WHERE lt.Language_Fluency = 'secondary'
            AND ult.UserId = u.UserId
            AND lt.LanguageId = ult.LanguageId) AS secondary_lang
FROM User_table u;

相关问题