簡體   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