Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL join tables multiple times

I have a table, with rows of events, and each one has (amongst lots of other fields) addedbyuser, editedbyuser, deletedbyuser There are INT, and refer back to the users table to a particular user. I am able to join one of the fields (say addedbyuser) without any problems, how do i join the rest and reference them in php?

events table:

eventid addedbyuser editedbyuser deletedbyuser
1       1           2            3

users table:

id username
1  name1
2  name2
3  name3

So basically, I want to display the names of who added, edited and deleted the article, can I do this in one SQL query?

like image 201
elef Avatar asked Jun 10 '11 03:06

elef


People also ask

Can we join same table twice in MySQL?

As you may know, it is used to join and combine data from two or more tables into one common data set. In this article, I'm going to discuss special types of joins? in which you combine the same table twice—including joining a table to itself, also known as the self join.

Can you join to the same table twice in SQL?

In a given explore, each join name must be unique. To self join the same table multiple times you can use the from parameter, as mentioned in the docs, to change the "join" name of the table. In this example, we join in person to order twice, with different names and different joining dimensions.

Can we use join for more than 2 tables?

Often, we need to get data from three or more tables to get some meaningful information. This can be accomplished using a multiple-table join. Data can be retrieved using different types of joins like INNER JOIN, LEFT JOIN, or both based on different requirements.

Is join faster than two queries?

I won't leave you in suspense, between Joins and Subqueries, joins tend to execute faster. In fact, query retrieval time using joins will almost always outperform one that employs a subquery. The reason is that joins mitigate the processing burden on the database by replacing multiple queries with one join query.


1 Answers

Something like this:

select 
    evn.eventid, 
    us1.username as addedbyuser, 
    us2.username as editedbyuser, 
    us3.username as deletedbyuser, 
from events evn
    join users as us1 on
        evn.addedbyuser = us1.id
    join users as us2 on
        evn.editedbyuser = us2.id
    join users as us3 on
        evn.deletedbyuser = us3.id
like image 150
Alex Aza Avatar answered Sep 18 '22 13:09

Alex Aza