我有两张桌子:
演示

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

状态
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'

请告诉我我的问题出在哪里。?

最佳答案

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

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有效

关于postgresql - 如何使用SQL Join获取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48421059/

10-11 02:53