phpmysql

Efficient way to calculate number of foreign keys in second table and display it with rows from first table - PHP - MySQL


I have two tables tablea and tableb like below;

tablea

+--------+-------+-------+-------+------+
|   fa   |   fb  |  fc   |  fd   |  fe  |
+--------+-------+-------+-------+------+
|  col1  |  f11  |  f12  |  f13  |  x1  |
+--------+-------+-------+-------+------+
|  col2  |  f21  |  f22  |  f23  |  x2  |
+--------+-------+-------+-------+------+
|  col3  |  f31  |  f32  |  f33  |  x3  |
+--------+-------+-------+-------+------+
|  col4  |  f41  |  f42  |  f43  |  x4  |
+--------+-------+-------+-------+------+

tableb

+--------+-------+-------+-------+------+
|  tbba  |  tbbb |  tbbc |  tbbd | tbbe |
+--------+-------+-------+-------+------+
|  cola  |  fa1  |  fa2  |  fa3  |  x1  |
+--------+-------+-------+-------+------+
|  colb  |  fb1  |  fb2  |  fb3  |  x1  |
+--------+-------+-------+-------+------+
|  colc  |  fc1  |  fc2  |  fc3  |  x1  |
+--------+-------+-------+-------+------+
|  cold  |  fd1  |  fd2  |  fd3  |  x2  |
+--------+-------+-------+-------+------+
|  cole  |  fe1  |  fe2  |  fe3  |  x2  |
+--------+-------+-------+-------+------+
|  colf  |  ff1  |  ff2  |  ff3  |  x3  |
+--------+-------+-------+-------+------+
|  colg  |  fg1  |  fg2  |  fg3  |  x3  |
+--------+-------+-------+-------+------+
|  colh  |  fh1  |  fh2  |  fh3  |  x3  |
+--------+-------+-------+-------+------+
|  coli  |  fi1  |  fi2  |  fi3  |  x3  |
+--------+-------+-------+-------+------+
|  colj  |  fj1  |  fj2  |  fj3  |  x4  |
+--------+-------+-------+-------+------+

I want to generate a table like;

+--------+-------+-----+
|  col1  |  f11  |  3  |
+--------+-------+-----+
|  col2  |  f21  |  2  |
+--------+-------+-----+
|  col3  |  f31  |  4  |
+--------+-------+-----+
|  col4  |  f41  |  1  |
+--------+-------+-----+

The number denotes the times where entry in fe field of tablea appears in tableb. Currently, I am fetching all rows from the tablea, and in each loop, I use another query to get number of rows in tableb, using tablea's fe field. Thus, I have 1 main query, and 4 sub queries. Is there any efficient way like join or something?


Solution

  • Try this:

    SELECT a.fa , a.fb , COUNT( b.tbbe) 
    FROM  tablea a
    LEFT JOIN tableb b ON a.fe = b.tbbe
    GROUP BY a.fa