连接两个表时,不计算空值

时间:2016-07-08 14:20:39

标签: php mysql null

我有两个名为vserversnodes的表:

vservers

vserverid **PK** | nodeid **FK** 
1              5
2              6
3              7

nodes

nodeid | name     | maxvps
5       some_name    4
6       some_name    4
7       some_name    4

因此,如果有一些vservers没有值,则不会通过PHP计算或获取它们。

SELECT nodes.name as name, COUNT(vservers.vserverid) as count_vps ,nodes.maxvps
FROM nodes, vservers
WHERE vservers.nodeid = nodes.nodeid
AND nodes.name LIKE 'some_name%'
GROUP BY name

我的第二种方法也是如此,但它返回相同的结果:

SELECT nodes.name as name, COUNT(*)- COUNT(vservers.vserverid) as count_vps, nodes.maxvps
FROM nodes, vservers
WHERE vservers.nodeid = nodes.nodeid
AND nodes.name LIKE 'some_name%'
GROUP BY name

但它仍然给出相同的结果 - 不包括空值。 编辑: 到目前为止,我已经认为NULL值不算数。所以有一个函数ISNULL可以计算NULL和实际值。问题是我不知道如何实现它。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您需要LEFT JOIN而不是INNER JOIN

SELECT nodes.name as name, COUNT(vservers.vserverid) as count_vps ,nodes.maxvps
FROM vservers
LEFT JOIN nodes ON(vservers.nodeid = nodes.nodeid AND nodes.name LIKE 'some_name%')
GROUP BY name

答案 1 :(得分:0)

我找到了解决方案。

var method = AppUser.prototype;

function AppUser(name) {
    this._name = name;
}

method.getName = function() {
    return this._name;
};

//scopes
method.getScopes = function() {
    //return the array of scope string values
};
method.setScopes = function(scopes) {
    //set the new scopes array to be the scopes array for the AppUser instance
    //if the AppUser instance already has a scopes array, delete it first
};
method.addScope = function(scope) {
    //check to see if the value is already in the array
    //if not, then add new scope value to array
};
method.removeScope = function(scope) {
    //loop through array, and remove the value when it is found 
}

module.exports = AppUser;  

现在也包含0值的那些。谢谢你们。 :)