我正在研究电子词典,我有2张桌子:
第一张表:条款
+----+--------------+ | id | term_text | +----+--------------+ | 1 | hello | | 2 | how are you? | | 3 | hola | +----+--------------+
第二张表:字典
<pre>
+-----------+------------+
| term_id_1 | term_id_2 |
+-----------+------------+
| 1 | 3 | /* hello - hola
| 2 | NULL | /* how are you? - NULL
+-----------+------------+
</pre>
我想这样显示:
<pre>
+--------------+-------------+
| term_text_1 | term_text_2 |
+--------------+-------------+
| hello | hola |
| how are you? | NULL |
+--------------+-------------+
</pre>
我正尝试使用以下查询获取数据:
<pre>
SELECT t1.term_text_1, t2.term_text_2
FROM dictionary d, term t1, term t2
WHERE d.term_id_1 = t1.id
AND d.term_id_2 = t2.id
</pre>
但是我只得到值不为null的地方!
答案 0 :(得分:1)
您可以使用LEFT JOIN
SELECT t1.term_text as term_text_1, t2.term_text as term_text_2
FROM dictionary d
LEFT JOIN term t1 ON d.term_id_1 = t1.id
LEFT JOIN term t2 ON d.term_id_2 = t2.id
答案 1 :(得分:1)
您需要两次将dictionary
与term
一起加入:
select
t1.term_text term_text_1,
t2.term_text term_text_2
from dictionary
left join term t1 on t1.id = term_id_1
left join term t2 on t2.id = term_id_2
请参见demo。
结果:
| term_text_1 | term_text_2 |
| ------------ | ----------- |
| hello | hola |
| how are you? | |