PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 14, 2022

[FIXED] SQL Query to join multiple tables

 February 14, 2022     mysql, php, yii     No comments   

Issue

I have 4 tables that I need to connect in order to get the reports that I need. But I'm confused on how to write the query. Below are the sample of the tables:

Client Table

client_id  |  client_name  |  con_id
----------:|:-------------:|:-------
    1      |     ABC       |  1
    2      |     DEF       |  1
    3      |     GHI       |  2

Consultant

con_id  |  con_name
-------:|:---------
   1    |    Ani
   2    |   Robby

Perm

pid  |  client_id  |  date
----:|:-----------:|:-----------
 1   |      1      |  2014-08-09
 2   |      1      |  2014-03-02
 3   |      2      |  2014-03-02 

Temp

tid  |  client_id  |  date
----:|:-----------:|:-----------
 1   |     2       |  2013-02-09
 2   |     3       |  2011-03-02
 3   |     3       |  2012-04-02 

The end result of the report that I want to show is something like this:

client_id  |  client_name  |  perm(COUNT)  |  temp(COUNT)  |  con_name
----------:|:-------------:|:-------------:|:-------------:|:---------
    1      |       ABC     |       2       |         0     |    Ani
    2      |       DEF     |       1       |         1     |    Ani
    3      |       GHI     |       0       |         2     |    Robby

I'm trying to use the LEFT OUTER JOIN, but I don't get the result that I want. Can anyone help me to figure out the query?


Solution

this is a simple outer join query with count and group by,just join your client table with the related ones and count only the distinct associations

select 
c.client_id,
c.client_name,
count(distinct p.pid) perm_count,
count(distinct t.tid) temp_count,
cn.con_name
from client c
left join Consultant cn on(c.con_id = cn.con_id)
left join Perm p on(c.client_id = p.client_id)
left join `Temp` t on(c.client_id = t.client_id)
group by c.client_id 

Fiddle Demo



Answered By - M Khalid Junaid
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing