sql与mysql中2个表数据进行匹配,MySQL左联接:从一个表中选择所有内容,但仅将第二个表中的值与条件匹配...

I have two tables. I want to select everything from one table and the matching row from the second table - that matches a criteria.

So tblConfig_Group contains a list of groups.

|ID | groupCode |

|1 | A |

|2 | B |

|3 | C |

|4 | D |

And tblConfig_CustomerGroup contains a list of groups and customers in that those groups.

|ID | groupCode | customerID |

|1 | A | 74 |

|2 | B | 74 |

|3 | A | 235 |

|4 | C | 74 |

It should only display rows from the second table where there is a match

AND criteria (customerID = 74)

EXPECTED RESULTS:

|ID | groupCode | customerID |

|1 | A | 74 |

|2 | B | 74 |

|3 | C | 74 |

|4 | D | |

I've tried a number of queries but it doesn't seem to work for me...

SQL Query 1:

SELECT g.groupCode, cg.customerID FROM tblConfig_Group g

LEFT JOIN tblConfig_CustomerGroup cg ON g.groupCode = cg.groupCode

WHERE cg.customerID = '74'

ACTUAL RESULTS: rows 1, 2 & 3.

| groupCode | customerID |

| A | 74 |

| B | 74 |

| A | 74 |

SQL Query 2:

SELECT g.groupCode, cg.customerID FROM tblConfig_Group g

left outer join tblConfig_CustomerGroup cg on g.groupCode = cg.groupCode

WHERE cg.customerID = '74'

UNION

SELECT g.groupCode, cg.customerID

FROM tblConfig_Group g

right outer join tblConfig_CustomerGroup cg on g.groupCode = cg.groupCode

ACTUAL RESULTS: rows 1, 2 & 3 + customer 235

| groupCode | customerID |

| A | 74 |

| B | 74 |

| A | 74 |

| A | 235 |

解决方案

SELECT

g.id,

g.groupCode,

cg.customerID

FROM tblConfig_Group g

LEFT JOIN tblConfig_CustomerGroup cg

ON g.groupCode = cg.groupCode

AND cg.customerID = '74';

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值