简体   繁体   中英

how write sql query with multiple join?

I have fours tables and I wanted to join all three tables with the one table.

I have listed my problem as follows:

Tables:

  1. users
  2. user_training
  3. user_courses
  4. user_certificates

I wanted to get the data from [2,3,4] tables that user_id field matches with the users table ID field.

When I try the INNER JOIN it gives me the result for users that are common in all the tables, But I just wanted to check the [2,3,4] tables with the table [1] Records.

My Query...

SELECT  A.training_name AS 'training_name', C.course_name AS 'course_name',   D.certificate_name AS 'certificate_name'
FROM user_training AS A INNER JOIN users AS B ON A.user_id=B.ID INNER JOIN user_courses AS C ON B.ID = C.user_id INNER JOIN user_certificates AS D ON B.ID = D.user_id;

Thanks in Advance.

use left join

    select u.* from users u 
    left join user_training ut on ut.user_id=u.user_id 
    left join user_courses uc on uc.user_id=u.user_id 
    left join user_certificates uct on uct.user_id=u.user_id

With this one you are getting all users and their respective trainings:

SELECT *
FROM `users`
LEFT JOIN `user_training` ON `users`.`id` = `user_training`.`user_id`

Changing *_trainig to *_courses or *_certificates will return all users with respected courses or certificates.

If you need to get data in one query, try this one:

SELECT *
FROM `users`
LEFT JOIN `user_training` ON `users`.`id` = `user_training`.`user_id`
LEFT JOIN `user_courses` ON `users`.`id` = `user_courses`.`user_id`
LEFT JOIN `user_certificates` ON `users`.`id` = `user_certificates`.`user_id`

If user has no trainings, courses, certificates all remaining fields will be null -ed.

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