[英]Join Three tables in mysql with weird requirement
我的數據庫中有三個表。
Table A
具有字段
KEYID | KeyName
27 | Income
28 | Account Number
Table B
中的字段
UserID | Email | Name | Phone
481 | test@gmail.com | test | 99999999
Table C
具有字段
ID | KEYID | UserID | Value
1 | 27 | 481 | 10,000
我需要顯示表字段的標題是:
UserID | Email | Name | Phone | Income
並且表值應如下所示:
481 | test@gmail.com | test | 99999999 | 10,000
我可以獲得應該在表中顯示的KeyID。 在此示例中,KeyIDs字符串為'27'。 我嘗試加入,我可以獲取並在表中顯示值。 但我不知道如何顯示表頭的鍵名。
任何想法。?
您可以使用一對內部聯接
select b.UserID, b.Email , b.Name, c.value as income
from tableB as b inner join tableC as C on b.userID = c.userId
inner join tableA as a on a.keyID = c.keyID
and a.keyname = 'Income';
以及您在評論中提供的查詢
select
b.UserID
, b.Email
, b.Name
, Group_Concat(Distinct Concat(c.keyID,’^:^’,c.value)
Order By c.id Separator ‘;’) As Keyvalues
from tableB as b
inner join tableC as C on b.userID = c.userId
inner join tableA as a on a.keyID = c.keyID;
並與CASE應該是
select
b.UserID
, b.Email
, b.Name
, Group_Concat(Distinct CASE
WHEN c.keyID IN ('1,23,10') THEN Concat(c.keyID,’^:^’,c.value) END
Order By c.id Separator ‘;’) As Keyvalues
from tableB as b
inner join tableC as C on b.userID = c.userId
inner join tableA as a on a.keyID = c.keyID;
該查詢應有助於獲得所需的結果。
select b.UserID, b.Email, b.Name, b.Phone, c.Value as Income
from table_b as b
JOIN table_c as c ON (b.UserID = c.UserID)
where c.KEYID = 27
嘗試這個:
SELECT b.userid, b.email, b.name, b.phone, c.value as income
FROM a
LEFT JOIN c on c.keyid = a.keyid
LEFT JOIN b ob b.userid = c.userid
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.