简体   繁体   English

在具有奇怪要求的mysql中加入三个表

[英]Join Three tables in mysql with weird requirement

I have three tables in my db. 我的数据库中有三个表。

Table A has the fields Table A具有字段

KEYID | KeyName
27    | Income
28    | Account Number

Table B has the fields Table B中的字段

UserID | Email          | Name | Phone
481    | test@gmail.com | test | 99999999

Table C has the fields Table C具有字段

ID | KEYID | UserID | Value
1  |   27  |   481  | 10,000

I need to display the table fields headers are: 我需要显示表字段的标题是:

UserID | Email          | Name |   Phone  | Income

and the table values should be like this: 并且表值应如下所示:

 481   | test@gmail.com | test | 99999999 | 10,000

I can get the KeyIDs which should be displayed in the table. 我可以获得应该在表中显示的KeyID。 In this example the KeyIDs string is '27' . 在此示例中,KeyIDs字符串为'27'。 I tried with joining and i can fetch & display the value in the table. 我尝试加入,我可以获取并在表中显示值。 but i dont know how i can show the key name as table header. 但我不知道如何显示表头的键名。

Any Idea.? 任何想法。?

You can use a pair of inner join 您可以使用一对内部联接

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';     

and the query you provided in comment 以及您在评论中提供的查询

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;  

and with CASE should be 并与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; 

This query should help to get your desire result. 该查询应有助于获得所需的结果。

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

Try this: 尝试这个:

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.

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