您需要使用LEFT JOIN。並且任何ci
列的每個條件都必須在ON子句中(否則,LEFT JOIN將轉換爲INNER JOIN)。而且你必須計數ci.CUSTOMER_ID
而不是cm.CUSTOMER_ID
。
SELECT cm.CUSTOMER_ID, COUNT(ci.CUSTOMER_ID) COUNT
FROM customer_master cm
LEFT JOIN customer_issue_details ci
ON ci.customer_id = cm.CUSTOMER_ID
AND ci.ACTUAL_DATE_RETURN < ci.RETURN_DATE
WHERE CUSTOMER_NAME LIKE 'r%'
GROUP BY cm.`CUSTOMER_ID`;
內連接(JOIN是INNER JOIN的別名)將從cm
表過濾掉任何行,如果沒有從ci
錶行已發現匹配聯接條件(如果你使用不要緊USING
或ON
)。 LEFT JOIN將從cm
表中返回至少一行,但如果ci
表中沒有找到匹配JOIN條件的行,則ci
表中的所有列都將爲NULL。
實施例:
cm:
| customer_id |
|-------------|
| 1 |
| 2 |
| 3 |
ci:
| customer_id |
|-------------|
| 1 |
| 1 |
| 2 |
INNER JOIN:
SELECT cm.customer_id as `cm.customer_id`, ci.customer_id as `ci.customer_id`
FROM cm
JOIN ci
ON ci.customer_id = cm.customer_id;
| customer_id | customer_id |
|-------------|-------------|
| 1 | 1 |
| 1 | 1 |
| 2 | 2 |
LEFT JOIN:
SELECT cm.customer_id, ci.customer_id
FROM cm
LEFT JOIN ci
ON ci.customer_id = cm.customer_id;
| customer_id | customer_id |
|-------------|-------------|
| 1 | 1 |
| 1 | 1 |
| 2 | 2 |
| 3 | (null) |
fiddle
隨着GROUP BY cm.customer_id
和COUNT(ci.customer_id)
您可以計算每個找到的行數cm.customer_id
。
SELECT cm.customer_id, COUNT(ci.customer_id)
FROM cm
LEFT JOIN ci
ON ci.customer_id = cm.customer_id
GROUP BY cm.customer_id
| customer_id | COUNT(ci.customer_id) |
|-------------|-----------------------|
| 1 | 2 |
| 2 | 1 |
| 3 | 0 |
fiddle
它返回0
爲cm.customer_id = 3
因爲COUNT只計算不爲空值。
如果您使用COUNT(cm.customer_id)
而不是cm.customer_id = 3
,您將獲得1
,因爲它不是NULL。現在,如果你有一列的任何條件ci
表(如ci.customer_id < 2
),你把它的WHERE子句中fiddle
,不匹配條件的所有行都會被過濾掉。
SELECT cm.customer_id, ci.customer_id
FROM cm
LEFT JOIN ci
ON ci.customer_id = cm.customer_id
WHERE ci.customer_id < 2
| customer_id | customer_id |
|-------------|-------------|
| 1 | 1 |
| 1 | 1 |
但移動該條件爲LEFT JOIN ON子句你保持每個cm.customer_id
至少一排,因爲這是多麼LEFT JOIN的作品。
SELECT cm.customer_id, ci.customer_id
FROM cm
LEFT JOIN ci
ON ci.customer_id = cm.customer_id
AND ci.customer_id < 2
| customer_id | customer_id |
|-------------|-------------|
| 1 | 1 |
| 1 | 1 |
| 2 | (null) |
| 3 | (null) |
現在GROUP BY
和COUNT
:
SELECT cm.customer_id, COUNT(ci.customer_id)
FROM cm
LEFT JOIN ci
ON ci.customer_id = cm.customer_id
AND ci.customer_id < 2
GROUP BY cm.customer_id;
| customer_id | COUNT(ci.customer_id) |
|-------------|-----------------------|
| 1 | 2 |
| 2 | 0 |
| 3 | 0 |
sqlfiddle
@Stone:請參閱SQL小提琴。 – wilx
@wix ...謝謝兄弟...在我的sqlYog它的輸出爲任何計數> 0但不是計數= 0 .....在你的小提琴如果你改變'%r'爲'%a'它是甚至沒有顯示輸出表,但它應該已經給出了0下的表名 – Stone
@Stone:我不明白你在說什麼。請詳細說明。 – wilx