如何使用SQL Join获取数据

时间:2018-01-24 11:10:54

标签: postgresql left-join

我有两张桌子:

demo_tbl

 name | banch| gender  | add_by |
================================
name1 |   ME |  Male   | admin1 |
name2 |  CSE |  Female | admin1 |    
name3 |   ME |  Male   | admin2 |
name4 |   CSE|  Male   | admin3 |

status_tbl

name   | status |
=================
name1  |    1   | 
name3  |    1   |

我想加入这两个表,输出应该如下。

name  | status | Gender |
=========================
name1 |    1   |  Male  |
name2 |        |  Female|
name3 |    1   |  Male  |

但我无法通过以下查询获得此输出。

SELECT demo_tbl.name, demo_tbl.gender, status_tbl.status
FROM demo_tbl LEFT JOIN status_tbl ON demo_tbl.name=status_tbl.name 
AND demo_tbl.add_by = 'admin1' AND status_tbl.status = '1'

请有人告诉我我的查询有什么问题。?

1 个答案:

答案 0 :(得分:0)

要获得所需的输出,查询应为:

SELECT demo_tbl.name, demo_tbl.gender, status_tbl.status
FROM demo_tbl 
LEFT JOIN status_tbl 
ON demo_tbl.name=status_tbl.name AND status_tbl.status = '1'
where demo_tbl.add_by in('admin1', 'admin2')

也许您只为name1name2获得了输出,因为您的条件demo_tbl.add_by = 'admin1'仅适用于name1name2