简体   繁体   English

MySQL将基于另一列的值在两个列中显示为“ 0”的两个表联接

[英]MySQL Join two tables displaying '0' in one column based on another column's value

I have two tables."login" and "acc_reg_num". 我有两个表。“登录”和“ acc_reg_num”。

"login" table has two columns: 'account_id' and 'userid'. “登录”表具有两列:“ account_id”和“ userid”。 (Using prefix "l") (使用前缀“ l”)
"acc_reg_num" has three: 'accound_id', 'key' and 'value'. “ acc_reg_num”具有三个:“ accound_id”,“ key”和“ value”。 (Using prefix "a") (使用前缀“ a”)

I need to join the column "a.value" to the "login" table. 我需要将列“ a.value”加入“登录”表。 Depending on the value in "a.key": If "a.key" is "SAMPLEVALUE" then use the value in "a.value". 取决于“ a.key”中的值:如果“ a.key”为“ SAMPLEVALUE”,则使用“ a.value”中的值。 But, if "a.key" is [Anything else] then place a "0" in "a.value" instead 但是,如果“ a.key”为[其他],则应在“ a.value”中放置“ 0”

I hope this is clear. 我希望这很清楚。 My current Query looks like this but it's showing duplicate results and values in "a.value" regardless "a.key" is "SAMPLEVALUE" or not. 我当前的查询看起来像这样,但是无论“ a.key”是否为“ SAMPLEVALUE”,它都在“ a.value”中显示重复的结果和值。

SELECT l.account_id, l.userid, a.value AS 'CashPoints'
FROM login AS l
LEFT JOIN acc_reg_num AS a ON a.account_id = l.account_id

I also need no duplicates for the l.account_id and l.userid columns. 我也不需要l.account_id和l.userid列的重复项。

You can add the a.key='SAMPLEVALUE' condition to the existing ON condition: 您可以将a.key='SAMPLEVALUE'条件添加到现有的ON条件中:

SELECT l.account_id, l.userid, COALESCE(a.value, 0) AS 'CashPoints'
FROM
  login AS l LEFT JOIN acc_reg_num AS a
  ON a.account_id = l.account_id AND a.key='SAMPLEVALUE'

in case there's no SAMPLEVALUE the join won't succeed and a.value will be NULL, then you can use COALESCE to get 0 instead of NULL. 如果没有SAMPLEVALUE,联接将不会成功,并且a.value将为NULL,那么您可以使用COALESCE来获取0而不是NULL。

You can use a CASE statement for this like 您可以使用CASE语句,例如

SELECT l.account_id, l.userid, 
CASE WHEN a.key = 'SAMPLEVALUE' THEN a.value ELSE '0' END AS 'CashPoints'
FROM login AS l
LEFT JOIN acc_reg_num AS a ON a.account_id = l.account_id

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

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