How to select a table that have one to another and another table relationship

I don’t know if the question make sense or not.
I’m trying to request information from 2 different tables that are linked (via FK) to a table and display the data with information from that linked tables.

post

+--------+--------+---------+-------------+  
| postid | userid | title   | description |  
+--------+--------+---------+-------------+  
| 1      | 1      | example | example     |  
+--------+--------+---------+-------------+  
| 2      | 2      | example | example     |  
+--------+--------+---------+-------------+  
| 3      | 3      | example | example     |  
+--------+--------+---------+-------------+

user

+--------+----------+--------+  
| userid | username | roleid |  
+--------+----------+--------+  
| 1      | admin    | 1      |  
+--------+----------+--------+  
| 2      | helper   | 1      |  
+--------+----------+--------+  
| 3      | test     | 2      |  
+--------+----------+--------+

role

+--------+---------------+  
| roleid | role          |  
+--------+---------------+  
| 1      | administrator |  
+--------+---------------+  
| 2      | default       |  
+--------+---------------+

Is there a way to select/show this table?:
result

+----+--------------+---------------+---------+
| id | creator_name | creator_role  | title   |
+----+--------------+---------------+---------+
| 1  | admin        | administrator | example |
+----+--------------+---------------+---------+
| 2  | helper       | administrator | example |
+----+--------------+---------------+---------+
| 3  | test         | default       | example |
+----+--------------+---------------+---------+

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try this:

    select a.postid id, b.username creator_name, c.role creator_role, a.title
    from `post` a
    left join `user` b on (a.userid = b.userid)
    left join `role` c on (b.roleid = c.roleid)

Method 2

Try this with joins

select u.userid id, u.username creator_name, r.role creator_role,  p.title  
from user u
inner join role r ON(u.roleid = r.roleid)
inner join post P ON (u.userid = p.userid)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x