0

我有这些表:

“用户”

id  email                name                 last_access
1   luca@gmail.com       Luca Pluto           2012-10-05 17:21:22.0
2   pippo@gmail.com      Irene Pippo          2012-10-05 17:22:25.0

'Nets_permissions'

user_id         network_id  perm
1               1234        3
1               1235        1
2               1235        3

我写了这个查询:

SELECT u.id, u.name, n.perm
FROM users as u LEFT OUTER JOIN nets_permissions as n
ON u.id = n.user_id
WHERE n.network_id=1234 AND n.perm <> 3

因为我想要已经拥有 network_id (1234) 权限的用户,但也需要没有 network_id 权限的用户。换句话说,我会有这个结果查询:

2    null    null

因为对于网络 1234,id=1 的用户 Luca Pluto 具有 perm=3,所以我想排除在外。相反,id=2 的用户 Irene Pippo 在 1234 网络上没有任何权限。所以它的行必须有 net_id 和 perm 设置为空。

我的查询结果为空。我不知道为什么。如果没有子句 n.perm <> 3 似乎工作得很好,但在空值之后也被遗漏了,不仅是 perm=3 的 rws。

我也尝试过这种方式:

SELECT u.id, u.name, n.perm FROM users as u LEFT OUTER JOIN 
(select * from nets_permissions WHERE network_id=1234) as n on u.id = n.user_id 
WHERE n.perm <> 3

but it doesn't work. without the WHERE clause all works. After no. The result query is empty.

How I can resolve this problem? I need that the perm column is a value or null, I can't remove this column.

4

4 回答 4

2

The right solution is:

SELECT u.id, u.name, n.perm FROM users as u LEFT OUTER JOIN 
(select * from nets_permissions WHERE network_id=1234) as n on u.id = n.user_id 
WHERE (n.perm <> 3 or n.perm is NULL)

Here Working with NULL Values there is a expanation of the treatment of NULL values in MySQL

Thank you all for your help!

于 2012-10-06T18:04:59.363 回答
1

Many SQL dialect use a special trinary logic with NULL the third possible value additional to true and false.

Anything compared to NULL results to NULL which in turn is handled as false.

So x = null will result in false for all x, just as x != null

If you want to include NULL values in the result you have to add special handling for that (Oracle syntax):

SELECT u.id, u.name, n.perm
FROM users as u LEFT OUTER JOIN nets_permissions as n
ON u.id = n.user_id
WHERE n.network_id=1234 
AND (n.perm <> 3 or n.perm is not null)
于 2012-10-06T11:43:01.067 回答
1
SELECT u.id, u.name, n.perm
FROM 
    users as u 
    LEFT OUTER JOIN 
    nets_permissions as n ON u.id = n.user_id 
WHERE 
    n.network_id = 1234 and n.perm <> 3
    or
    n.network_id <> 1234
    or
    n.network_id is null
于 2012-10-06T11:52:34.760 回答
1

I like users that user the "JOIN" syntax. It has additional benefit, aside from making the code easier to read, that people don't realize.

SELECT u.id, u.name, n.perm
FROM users as u LEFT OUTER JOIN nets_permissions as n
ON u.id = n.user_id
AND n.network_id=1234 
WHERE COALESCE(n.perm,-1) <> 3
于 2012-10-06T16:06:30.227 回答