同一个表的两个外键和多个JOIN与WHERE子句
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了同一个表的两个外键和多个JOIN与WHERE子句相关的知识,希望对你有一定的参考价值。
我有3个表的mysql数据库:
语言 lang_id lang
字 word_id lang_id字
翻译 trans_id word_id1 word_id2
我想获得我选择的两种语言之间的所有翻译。以下命令(语法错误)基于: Two foreign keys of the same table. How do I write this SELECT statement? MySQL multiple Inner Join with Where clause
在命令中,我试图获得语言1和2之间的翻译。
SELECT w1.word, lang1.lang AS w2.word, lang2.lang AS FULL
FROM translation AS trans
(JOIN (word AS w1 JOIN language AS lang1 ON lang1.id_lang=w1.lang_id)
ON trans.word_id1=w1.id_word WHERE (w1.lang_id=1 OR w1.lang_id=2))
(JOIN (word AS w2 JOIN language AS lang2 ON lang2.id_lang=w2.lang_id)
ON trans.word_id2=w2.id_word WHERE (w2.lang_id=1 OR w2.lang_id=2))
解决方案感谢@ ahmed-gdoma我想出了这个命令:
SELECT w1.word AS w1, l1.lang AS L1,w2.word AS w2, l2.lang AS L2 FROM translation AS t
JOIN word AS w1 on w1.id_word=t.word_id1
JOIN word AS w2 on w2.id_word=t.word_id2
JOIN language AS L1 on w1.lang_id=L1.id_lang
JOIN language AS L2 on w2.lang_id=L2.id_lang
WHERE (l2.id_lang=1 OR l2.id_lang=2)
AND (l1.id_lang=2 OR l1.id_lang=1)
它返回单词(w1),它的语言(L1),单词的翻译(w2)和翻译的语言(L2)
答案
问题是FULL
是MySQL中的reserved keyword,因此,你需要为你的AS
选择一个不同的名字。
在下面,我用COMBINED
替换它:
SELECT w1.word, lang1.lang AS w2.word, lang2.lang AS COMBINED
FROM translation AS trans
(JOIN (word AS w1 JOIN language AS lang1 ON lang1.id_lang=w1.lang_id)
ON trans.word_id1=w1.id_word WHERE (w1.lang_id=1 OR w1.lang_id=2))
(JOIN (word AS w2 JOIN language AS lang2 ON lang2.id_lang=w2.lang_id)
ON trans.word_id2=w2.id_word WHERE (w2.lang_id=1 OR w2.lang_id=2)
希望这可以帮助! :)
另一答案
SELECT w1.word AS L1,w2.word as L2 FROM translation AS t
JOIN word AS w1 on w1.word_id=t.word_id1
JOIN word AS w2 on w2.word_id=t.word_id2
以上是关于同一个表的两个外键和多个JOIN与WHERE子句的主要内容,如果未能解决你的问题,请参考以下文章