带计数的左连接返回一个结果

时间:2014-06-25 08:06:01

标签: mysql sql left-join

我有两张桌子。

|Table One: Adversitements-----------------------|
| ID |                                  ADVTITLE |
|----|-------------------------------------------|
|  1 |                   IT Staff will be taken. |
|  2 |  Human resources personnel will be taken. |
|  3 |               CNC Operator will be taken. |

|Table Two: Applications-----|
| ID | ADVID | APPLICANTNAME |
|----|-------|---------------|
|  1 |     1 |      John Doe |
|  2 |     1 |    John Doe 2 |
|  3 |     1 |      Jane Doe |
|  4 |     2 |      John Doe |
|  5 |     2 |      Jane Doe |
|  6 |     3 |      John Doe |

我想要结果:

|                ADVTITLE                   | APPLICANTCOUNT |
|-------------------------------------------|----------------|
| IT Staff will be taken.                   |              3 |
| Human resources personnel will be taken.  |              2 |
| CNC Operator will be taken.               |              1 |

但是返回一个结果;
输出:

|                ADVTITLE | APPLICANTCOUNT |
|-------------------------|----------------|
| IT Staff will be taken. |              6 |

MySQL查询;

SELECT adv.advtitle, COUNT(applications.id) as applicantCount 
FROM advertisements as adv 
LEFT JOIN applications 
ON adv.id = applications.advid 

所有列表都与申请人数量有关?

SQL小提琴链接:http://sqlfiddle.com/#!2/8644c/1/0

3 个答案:

答案 0 :(得分:1)

你错过了GROUP BY条款:

SELECT adv.advtitle, COUNT(applications.id) as applicantCount
FROM advertisements as adv
LEFT JOIN applications ON adv.id = applications.advid 
GROUP BY adv.advtitle
ORDER BY applicantCount desc

结果:

ADVTITLE                                   APPLICANTCOUNT
---------------------------------------------------------
IT Staff will be taken.                     3
Human resources personnel will be taken..   2
CNC Operator will be taken.                 1

Fiddle Example

答案 1 :(得分:0)

您需要GROUP BY子句

SELECT adv.advtitle, COUNT(applications.id) as applicantCount 
FROM advertisements as adv 
LEFT JOIN applications 
ON adv.id = applications.advid 
GROUP BY applications.advid 

SQL Fiddle

答案 2 :(得分:0)

我已经尝试将其粘贴到你的sqlfiddle中来测试它:)

SELECT A.advtitle,COUNT(B.advid) AS ApplicantCount FROM advertisements A
LEFT JOIN applications B ON B.advid = A.id
GROUP BY A.id