当某个表没有值时连接表?

时间:2010-08-19 07:50:13

标签: mysql drupal

我有这些表格:

USER TABLE
uid | name | role
    |      |
1   | bob  | package 1
2   | jill | package 2
3   | pam  | package 1

NODE TABLE
nid | uid | type
    |     |
1   | 1   | car
2   | 1   | car
3   | 1   | car
4   | 2   | page
5   | 1   | car
6   | 3   | car

如果我这样做:

select u.uid, u.name, count(nid) as totalNodes from USER as u left join NODE on n.uid = u.uid where n.type = 'car' group by u.uid

我最终得到了:

uid | name | totalNodes
    |      | 
1   | bob  | 4
3   | pam  | 1

换句话说,吉尔被排除在外。为什么?我怎么能避免这种情况?即我希望Jill也出现在列表中,但是totalNodes为0(甚至是NULL)。

2 个答案:

答案 0 :(得分:2)

您需要在尝试加入表之前执行聚合,因为您当前正在进行的操作是保持连接,然后限制数据(此时Jill被排除)然后进行分组。如果在子查询中执行计数和限制,则可以将这些结果连接到用户表以获得所需的输出:

SELECT u.uid, u.name, IFNULL(c.nodecount,0) AS `count`
FROM USER u LEFT JOIN (
    SELECT uid, `type` , COUNT(nid) AS nodecount
    FROM node
    WHERE TYPE = 'car'
    GROUP BY uid, type
) AS c ON u.uid = c.uid

答案 1 :(得分:0)

使用RIGHT JOIN代替,

尝试:

select u.uid, u.name, count(nid) as totalNodes from USER as u
right join NODE on n.uid = u.uid where n.type IS NULL or n.type = 'car' group by n.uid

看到这篇优秀文章的联合视觉解释:

http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

join的语法:

http://dev.mysql.com/doc/refman/5.0/en/join.html