Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql join 3 tables and count

Please look at this image

alt text

here is 3 tables , and out i want is

uid from table1 industry from table 3 of same uid count of fid from table 2 of same uid

like in the sample example output will be 2 records

Thanks

like image 232
air Avatar asked Mar 27 '10 14:03

air


People also ask

Can I join 3 tables in MySQL?

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.

Can you cross join 3 tables in SQL?

At some point, you probably wondered if it's possible to join 3 tables in SQL or even more tables using the JOIN keyword. The short answer is, yes, it's possible! The longer answer is, yes, it's possible, and we will show you how to join 3 or more tables in SQL on a concrete job interview question.

When joining 3 tables in a select statement how many join conditions are needed in the where clause?

for joining two tables, we require 1 join statement and for joining 3 tables we need 2 join statements.


2 Answers

I don't see any relation with table 1. Here's an example using an inner join between the two tables and grouping by the uid:

SELECT 
  t3.uid, 
  t3.industry, 
  count(t2.fid) 
FROM 
  table3 t3 
INNER JOIN 
  table2 t2 ON t3.uid = t2.uid 
GROUP BY 
  t3.uid
like image 173
Darin Dimitrov Avatar answered Sep 23 '22 00:09

Darin Dimitrov


Try with this:

SELECT table1.uid,table3.industry,COUNT(table2.fid) 
FROM table1 
INNER JOIN table3 ON table1.uid=table3.uid
INNER JOIN table2 ON table1.uid=table2.uid
GROUP BY table1.uid, table3.industry

Table1 inner join is useless but could be useful if you'll need to retrieve city or mem_no; in this case, remember to add the field also in GROUP BY clause.

like image 22
systempuntoout Avatar answered Sep 23 '22 00:09

systempuntoout