简体   繁体   English

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

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

I need to show all records from table A per user_id in table B, even if not matched. 我需要显示表B中每个user_id的表A中的所有记录,即使不匹配也是如此。 I have tried with LEFT JOIN and GROUP-ing but did not achieved my expected result. 我已经尝试过LEFT JOIN和GROUP-ing,但没有达到我的预期结果。 Also my skill on SQL is not good, so need help. 另外我在SQL方面的技能也不好,因此需要帮助。

Here is my table data: 这是我的表格数据:

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    |
==================================

The result I expect is to see all results from left table per user_id on right, even if it doesn't exist in Right Table. 我期望的结果是,即使右表中不存在,每个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  |
==================================

Thank you. 谢谢。

You have to create artificial table containing list of all userId: 您必须创建包含所有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