加入mysql中有奇怪需求的三个表


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。在本例中,KeyID字符串为"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