所以我试图让这个陈述起作用:
SELECT
*
FROM
sakai.SAKAI_REALM AS sr
WHERE
sr.REALM_KEY = (SELECT DISTINCT
srrf.REALM_KEY
FROM
sakai.SAKAI_REALM_RL_FN AS srrf
WHERE
srrf.ROLE_KEY = 51);
但是我收到MySql错误1242,Subquery返回超过1行。我知道它会返回多行(它应该返回7)但有没有办法让这个查询起作用?我不怀疑我使用了错误的语法。
我正在尝试查找子查询中具有现有值的所有SAKAI_REALMS。
答案 0 :(得分:4)
尝试将=
更改为in
,这基本上代表了从子查询返回的集合中的值:
SELECT
*
FROM
sakai.SAKAI_REALM AS sr
WHERE
sr.REALM_KEY in (SELECT DISTINCT
srrf.REALM_KEY
FROM
sakai.SAKAI_REALM_RL_FN AS srrf
WHERE
srrf.ROLE_KEY = 51);
答案 1 :(得分:1)
使用联接,您可以执行以下操作:
SELECT sr.*
FROM sakai.SAKAI_REALM AS sr
INNER JOIN
(
SELECT DISTINCT srrf.REALM_KEY
FROM sakai.SAKAI_REALM_RL_FN AS srrf
WHERE srrf.ROLE_KEY = 51
) m ON sr.REALM_KEY = m.REALM_KEY
或者,如果子查询可能返回多个记录,则使用:
SELECT *
FROM sakai.SAKAI_REALM AS sr
WHERE sr.REALM_KEY IN
(
SELECT srrf.REALM_KEY
FROM sakai.SAKAI_REALM_RL_FN AS srrf
WHERE srrf.ROLE_KEY = 51
);
或者,强制它仅使用LIMIT 1
返回一条记录:
SELECT *
FROM sakai.SAKAI_REALM AS sr
WHERE sr.REALM_KEY =
(
SELECT srrf.REALM_KEY
FROM sakai.SAKAI_REALM_RL_FN AS srrf
WHERE srrf.ROLE_KEY = 51
LIMIT 1
);