简体   繁体   中英

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. I have tried with LEFT JOIN and GROUP-ing but did not achieved my expected result. Also my skill on SQL is not good, so need help.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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