我需要显示表B中每个user_id的表A中的所有记录,即使不匹配也是如此。我已经尝试过LEFT JOIN和GROUP-ing,但没有达到我的预期结果。另外我在SQL方面的技能也不好,因此需要帮助。
这是我的表格数据:
Table A : gateways
=========================
| ID | Gateway |
=========================
| 1 | Paypal |
| 2 | Webpay |
| 3 | Stripe |
=========================
Table B : gateway_user
==================================
| GatewayID | UserID | Active |
==================================
| 1 | 1 | Y |
| 1 | 2 | Y |
| 1 | 3 | N |
| 2 | 1 | Y |
| 2 | 2 | N |
| 3 | 1 | Y |
==================================
我期望的结果是,即使右边的表中不存在,每个右边的user_id也会从左边的表中看到所有结果。
==================================
| GatewayID | UserID | Active |
==================================
| 1 | 1 | Y |
| 1 | 2 | Y |
| 1 | 3 | N |
| 2 | 1 | Y |
| 2 | 2 | N |
| 2 | 3 | null |
| 3 | 1 | Y |
| 3 | 2 | null |
| 3 | 3 | null |
==================================
谢谢你。
您必须创建包含所有userId列表的人工表:
SELECT gw.id, ua.userId, gu.active
FROM gateways gw
JOIN (SELECT DISTINCT userId
FROM gateway_user) ua
LEFT JOIN gateway_user gu
ON gu.userId = ua.userId AND gu.gatewayId = gw.gatewayId
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句