如何在具有外部联接和分组依据的查询中包含NULL值

时间:2011-12-29 00:24:56

标签: mysql sql

我有两个包含以下示例数据的表:

Table 1: `item_name`
| item_id | item_desc |
| 1       | apple     |
| 2       | orange    |
| 3       | banana    |
| 4       | grape     |
| 5       | mango     |

Table 2: `user_items`
| user_id | item_id |
| 127     | 1       |
| 127     | 2       |
| 127     | 4       |
| 128     | 1       |
| 128     | 5       |

我正在尝试使用以下查询选择user_id 127和128中的每个item_id以及相应的item_desc:

SELECT IFNULL(COUNT(ui.user_id), 0) AS total, in.item_desc 
FROM user_items AS ui 
RIGHT OUTER JOIN item_name AS in 
    ON ui.item_id = in.item_id 
WHERE ui.user_id IN (127, 128) 
GROUP BY ui.item_id
ORDER BY total DESC

上述查询的结果是:

| total | item_desc |
| 2     | apple     |
| 1     | orange    |
| 1     | grape     |
| 1     | mango     |

但它不包括item_id 3,banana,我想用RIGHT OUTER JOIN检索它。我希望得到一个看起来像这样的结果:

| total | item_desc |
| 2     | apple     |
| 1     | orange    |
| 1     | grape     |
| 1     | mango     |
| 0     | banana    |

有没有办法修改查询以达到上面的预期结果? 谢谢你的时间。

2 个答案:

答案 0 :(得分:6)

您的查询使用count时出现了一点错误。这很有效。

select count(ui.item_id) as total, in.item_desc
from   item_name `in`
       left join user_items ui on ui.item_id = in.item_id
                                        and ui.user_id in (127, 128)
group by
       in.item_desc
order by total desc

答案 1 :(得分:4)

您的WHERE子句实际上是删除item_name中与user_id的127& 128.

为了解决这个问题,最简单的解决方案是LEFT JOINitem_name表到user_items表,然后在user_id表上选择JOINSELECT COUNT(*), itn.item_desc FROM item_name AS itn LEFT OUTER JOIN user_items AS ui ON ui.item_id = itn.item_id AND ui.user_id IN (127, 128) GROUP BY itn.item_desc

RIGHT OUTER JOIN

请注意,虽然这可以写成{{1}},但我发现这种类型的连接是反间谍的,并建议只在绝对必要时使用它们。