简体   繁体   中英

Joining columns in same table

I need to get data form table matching the column names and then joining that with the other table using foreign key. Here is the table structure:-

Table : user_master

id |   user_name      |   user_password   |  status
1  |   user_name_1    |       password     |    1
2  |   user_name_2    |       password     |    1
3  |   user_name_3    |       password     |    0

Table : user_meta

id | user_id  |  meta_key  |   meta_value
1  |    1     |   fname    |     kris
2  |    1     |   lname    |     tris
3  |    2     |   fname    |     mac
4  |    2     |   lname    |     book

Is if possible to get results like this ?

id |   user_name       |   user_password   |  status | fname  |  lname
1  |   user_name_1     |   password        |    1    | kris   |  tris
2  |   user_name_2     |   password        |    1    | mac    |  book

so that i can use the query and output the data like this

    foreach ($rows as $row) { 
        echo $row['id']
        ehco $row['fname'] .... and so on 

I am using this library for Database MySQLi query

Can you please help me on this if at all this is possible. Thanks in advance.

Try this:

Select 

id ,   user_name    , user_password  ,status 
(select  meta_value from user_meta um where um.user_id = umst.user_id and meta_key like 'fname') fname  , 
(select  meta_value from user_meta um where um.user_id = umst.user_id and meta_key like 'lname') lname
from 

user_master usmt

Use below query this will work for you.

SELECT u.id,u.user_name,u.user_password,u.status,
(CASE WHEN um.meta_key = 'fname'  THEN um.meta_value END) as fname,
(SELECT meta_value from user_meta WHERE meta_key = 'lname' AND user_id = u.id ) as lname
FROM `user_master` as u 
INNER JOIN user_meta as um 
ON um.user_id = u.id
GROUP BY id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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