Mysql加入同一个表不在的表

时间:2018-03-22 22:48:04

标签: mysql sql

我有一张这样的表

id  original    alias  lang
1   word1es     word1   es
2   word1en     word1   en
3   word2es     word2   es
4   word2fr     word2   fr
5   word3es     word3   es

es视为主郎 我需要检索alias语言中存在但不存在于其他语言中的所有条目(基于es列)

预期结果:

alias  lang
word1   fr
word2   en
word3   en
word3   fr

我试过了

SELECT B.alias, B.lang FROM my_table A
JOIN my_table B
ON B.alias NOT IN (A.alias)


SELECT B.alias, B.lang FROM my_table AS A
JOIN my_table AS B
ON
A.alias = B.alias
WHERE
B.alias IS NULL


SELECT B.alias, B.lang FROM my_table A
JOIN my_table B
ON A.alias <> B.alias

但没有一个没有返回预期的结果

2 个答案:

答案 0 :(得分:1)

我只想使用:

select t.*
from my_table t
where t.lang = 'es' and
      not exists (select 1 from my_table t2 where t2.alias = t.alias and t2.lang <> 'es');

另一种方法使用聚合:

select alias, max(lang)
from my_table
group by alias
having min(lang) = max(lang) and min(lang) = 'es';

如果唯一的语言是es,那么这将返回该别名。

答案 1 :(得分:1)

创建所有语言的列表可以提供帮助:

SELECT esWords.*, langs.lang 
FROM my_table AS esWords
/* join with all other language identifiers to simulate a 
   "what is it in this language?" question
*/
LEFT JOIN (SELECT DISTINCT lang FROM my_table) AS langs 
   ON esWords.lang <> langs.lang
/* left join with my_table again to find the words for other languages */
LEFT JOIN my_table AS otherWords 
   ON esWords.alias = otherWords.alias
   AND langs.lang = otherWords.lang
WHERE esWords.lang = 'es' 
   AND otherWords.id IS NULL /* filter out all languages where a 
                                word was found for that language
                              */

从技术上讲,您不需要在第一次加入中过滤掉原始语言;由于它始终匹配,因此最终otherWords.id IS NULL将始终将其过滤掉。