我的一个测试用例遇到了一个我无法解释的奇怪问题。它归结为一个应该返回 1 行的查询,而不是返回零。
这是失败的查询。
SELECT roles.id FROM `roles`
INNER JOIN `accounts_roles` ON `roles`.id = `accounts_roles`.role_id
WHERE (`roles`.`id` = 9)
AND (`accounts_roles`.account_id = 6 ) LIMIT 1;
11:24:07 [SELECT - 0 row(s), 0.001 secs] Empty result set fetched
这是我无法解释的部分。
如果我将 roles.id
更改为 *
我可以看到那里有数据。
SELECT * FROM `roles`
INNER JOIN `accounts_roles` ON `roles`.id = `accounts_roles`.role_id
WHERE (`roles`.`id` = 9)
AND (`accounts_roles`.account_id = 6 ) LIMIT 1;
id name authorizable_type authorizable_id created_at updated_at account_id role_id created_at updated_at
-- ----- ----------------- --------------- ------------------- ---------- ---------- ------- ------------------- ----------
9 owner Couple 1 2010-11-30 11:13:31 (null) 6 9 2010-11-30 11:13:31 (null)
为什么我选择的列会对返回的总行数产生影响?
这是有问题的两个表:
describe roles;
COLUMN_NAME COLUMN_TYPE IS_NULLABLE COLUMN_KEY COLUMN_DEFAULT EXTRA
----------------- ----------- ----------- ---------- -------------- --------------
id int(11) NO PRI (null) auto_increment
name varchar(40) YES (null)
authorizable_type varchar(30) YES (null)
authorizable_id int(11) YES MUL (null)
created_at datetime YES (null)
updated_at datetime YES (null)
describe accounts_roles;
COLUMN_NAME COLUMN_TYPE IS_NULLABLE COLUMN_KEY COLUMN_DEFAULT EXTRA
----------- ----------- ----------- ---------- -------------- -----
account_id int(11) YES MUL (null)
role_id int(11) YES MUL (null)
created_at datetime YES (null)
updated_at datetime YES (null)
最佳答案
我会将查询转移到以下内容...因为“角色”主键是 ID 列,永远不会重复,所以 1 的限制是不必要的。此外,我会将您的帐户 ID 限定符转移到连接子句中。
SELECT
roles.id
FROM
roles
INNER JOIN accounts_roles ar
ON roles.id = ar.role_id
AND ar.account_id = 6 )
WHERE
roles.id = 9
关于mysql - 带有 INNER JOIN 的 SELECT 子句影响行数的奇怪行为? (MySQL 5.1.52),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5263425/