繁体   English   中英

MySQL-从右表中的每个组获取左表中的所有行

[英]MySQL - Get all rows from left table per group on right table

我需要显示表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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM