MYSQL输出嵌套数据

时间:2014-04-24 14:55:57

标签: mysql sql

您好我在输出表中获得嵌套结果时遇到了问题。

SELECT *, users.Name FROM person WHERE person.User IN
( 
    SELECT Id FROM users WHERE users.Id = "0014082f-5e17-4eaa-aebc-a22800c59ccc"
)

在这个例子中,我想在人的数据旁边选择嵌套表用户的用户名。这段代码给出了以下错误

 #1054 - Unknown column 'users.Name' in 'field list'

但我该怎么做才能解决它?

编辑:

我试图简化一些事情但它只是让我的问题更加模糊 这是来自芒果的JOIN提示的原始代码

SELECT * FROM behandelaars LEFT JOIN
( 
    SELECT Id, Name FROM users WHERE users.Id 
    IN(
        SELECT User FROM usersinrole WHERE Role IN (
            SELECT Id FROM roles WHERE Name = "BeloningHintingSysteem"
        )
    )
    AND users.Id NOT IN(
        SELECT User FROM usersinrole WHERE Role IN (
            SELECT Id FROM roles WHERE Name = "UitgelslotenVanOnderzoek"
        )
    )
)
ON behandelaars.User = users.Id

THX Matthy

3 个答案:

答案 0 :(得分:1)

尝试JOIN -

SELECT person.*, users.Name FROM person 
INNER JOIN users ON person.User = users.Id
WHERE users.Id = "0014082f-5e17-4eaa-aebc-a22800c59ccc"

答案 1 :(得分:1)

我非常确定IN / ANY / SOME的子查询不允许使用子查询之外的子查询表。

在您的特定情况下,子查询非常简单,可以直接连接到主查询:

SELECT person.*, users.Name
    FROM person 
    LEFT JOIN users
      ON person.User = users.Id
    WHERE users.Id = "0014082f-5e17-4eaa-aebc-a22800c59ccc"

如果子查询变得更复杂或需要主查询不需要的分组/聚合,则可以加入子查询:

SELECT person.*, a_new_alias_for_users.Name
    FROM person 
    LEFT JOIN (
        SELECT Name
            FROM users
            WHERE users.Id = "0014082f-5e17-4eaa-aebc-a22800c59ccc"

    ) AS a_new_alias_for_users
    WHERE person.some_column <> 2;

答案 2 :(得分:0)

您的上一个查询返回ID,并且您正在将Role与ID进行比较。