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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With