显示来自另一个表的数据(如果存在)

时间:2016-05-26 12:12:33

标签: sql postgresql

我很难从我的数据库中获取正确的数据。

我有几张桌子:

events_template          laser_events
| id | something |       | id  | extid |   added   |
==================       ===========================
|  1 | something |       |  1  |   7   |   added   |
|  2 | something |       |  2  |   4   |   added   |
|  3 | something |       |  3  |   2   |   added   |
|  4 | something |       |  4  |   1   |   added   |
|  5 | something |       |  5  |   9   |   added   |
|  6 | something |       |  6  |   3   |   added   |
|  7 | something |
|  8 | something |
|  9 | something |
| 10 | something |
| 11 | something |
| 12 | something |
| 13 | something |
| 14 | something |

我想要做的是得到一些输出,它会显示两个表的结果,它们通过id和extid链接在一起,但是仍然显示来自events_template的结果,即使没有匹配的laser_events行。

我尝试过像

这样的东西
SELECT 
     id,  
     extid 
FROM 
     events_template, 
     laser_events 
WHERE 
     events_template.id = laser_events.ext_id;

但如果没有匹配的laser_events行,则不会向我显示events_template行。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

您必须使用LEFT JOIN

SELECT e.id, l.ext_id 
FROM events_template e
LEFT JOIN laser_events  l ON e.id = l.ext_id;