MDW_CUSTOMER_ACCOUNTS
包含以下字段:ACCOUNT_ID
,MEAL_ID
。
MDW_MEALS_MENU
包含以下字段:MEAL_ID
,MEAL_NAME
。
我正在尝试生成一份报告,说明客户使用该查询订阅特定餐点的次数,
SELECT count(a.account_id), b.meal_id, b.meal_name
FROM mdw_meals_menu b LEFT JOIN mdw_customer_accounts a
on b.meal_id=a.meal_id
WHERE
a.start_date BETWEEN to_date('01-APR-2013','DD-MON-YYYY')
AND to_date('30-JUN-2013','DD-MON-YYYY')
GROUP BY b.meal_id, b.meal_name
ORDER BY count(a.account_id) desc, b.meal_id;
这仅列出已订阅至少一次的MEAL_ID
。但它没有显示尚未订阅的ID。
如何在计数为MEAL_ID
的情况下打印这些0
?
我修改了代码,但仍然得到相同的结果。
答案 0 :(得分:4)
你的where子句有效地将你的外连接转回到内连接 - 外连接表上的条件通常应该在join子句中,如下所示:
SELECT count(a.account_id), b.meal_id, b.meal_name
FROM mdw_meals_menu b
LEFT JOIN mdw_customer_accounts a
on b.meal_id=a.meal_id and
a.start_date BETWEEN to_date('01-APR-2013','DD-MON-YYYY')
AND to_date('30-JUN-2013','DD-MON-YYYY')
GROUP BY b.meal_id, b.meal_name
ORDER BY count(a.account_id) desc, b.meal_id;
答案 1 :(得分:1)
您应该使用左外连接。