[英]How to calculate number of foreign keys in second table with a condition and display it with rows from first table - PHP - MySQL?
[英]Efficient way to calculate number of foreign keys in second table and display it with rows from first table - PHP - MySQL
我有兩個表tablea
和tableb
如下;
表A
+--------+-------+-------+-------+------+
| 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 |
+--------+-------+-------+-------+------+
表B
+--------+-------+-------+-------+------+
| 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 |
+--------+-------+-------+-------+------+
我想生成一個表
+--------+-------+-----+
| col1 | f11 | 3 |
+--------+-------+-----+
| col2 | f21 | 2 |
+--------+-------+-----+
| col3 | f31 | 4 |
+--------+-------+-----+
| col4 | f41 | 1 |
+--------+-------+-----+
數字表示tablea
fe
字段中的條目出現在tableb
。 當前,我正在從tablea
獲取所有行,並且在每個循環中,我使用tablea
的fe
字段使用另一個查詢來獲取tableb
的行數。 因此,我有1個主查詢和4個子查詢。 有什么有效的方法,例如加入或什么?
謝謝
嘗試這個:
SELECT a.fa , a.fb , COUNT( b.tbbe)
FROM tablea a
LEFT JOIN tableb b ON a.fe = b.tbbe
GROUP BY a.fa
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.