I have a SQL query which performs innerJoin
operation on 2 tables.
Table 1: user
Table 2: local_auth
The query returns all the matching rows based on the user_id
key
async getUser(id) {
return camelizeKeys(
await knex
.select(
'u.id',
'u.first_name',
'u.last_name',
'u.username',
'u.image_url',
'u.is_admin',
'u.phone',
'u.info',
'la.email'
)
.from('user AS u')
.leftJoin('local_auth AS la', 'la.user_id', 'u.id')
.where('u.id', '=', id)
.first()
);
}
Now, what I have to do is to modify the above query so that it performs the join operation on 3 tables.
Table 3: customer_user
There is another table called customer_user
, which has user_id
as one of the foreign key. How do I retrieve some fields from customer_user
table based on the user_id
. I would like to perform something like this (but of course the following won’t work due to the incorrect way of performing multiple joins using knex)
async getUser(id) {
return camelizeKeys(
await knex
.select(
'u.id',
'u.first_name',
'u.last_name',
'u.username',
'u.image_url',
'u.is_admin',
'u.phone',
'u.info',
'la.email',
'cu.customer_id',
'cu.department_id'
)
.from('user AS u')
.leftJoin('local_auth AS la', 'la.user_id', 'u.id')
.leftJoin('customer_user AS cu', 'cu.user_id', 'u.id')
.where('u.id', '=', id)
.first()
);
}
Note: Due to the limitation of adding a table
markup on SO, I have attached the screenshot instead.
It is possible to use multiple join statements together to join more than one table at the same time. To do that you add a second INNER JOIN statement and a second ON statement to indicate the third table and the second relationship.
The syntax for multiple joins: SELECT column_name1,column_name2,.. FROM table_name1 INNER JOIN table_name2 ON condition_1 INNER JOIN table_name3 ON condition_2 INNER JOIN table_name4 ON condition_3 . . . Note: While selecting only particular columns use table_name.
Can you LEFT JOIN three tables in SQL? Yes, indeed! You can use multiple LEFT JOINs in one query if needed for your analysis. In this article, I will go through some examples to demonstrate how to LEFT JOIN multiple tables in SQL and how to avoid some common pitfalls when doing so.
Actually, the query works just fine. Due to syntax error, I wasn't able to execute it
async getUser(id) {
return camelizeKeys(
await knex
.select(
'u.id',
'u.first_name',
'u.last_name',
'u.username',
'u.image_url',
'u.is_admin',
'u.phone',
'u.info',
'la.email',
'cu.customer_id',
'cu.department_id'
)
.from('user AS u')
.leftJoin('local_auth AS la', 'la.user_id', 'u.id')
.leftJoin('customer_user AS cu', 'cu.user_id', 'u.id')
.where('u.id', '=', id)
.first()
);
}
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