0

在我从带有 COALESCE 的 SELECT 中获得结果后,我试图加入一个表

SELECT
    COALESCE(
            (
                SELECT
                      relocations.location_id
                FROM
                      relocations
                WHERE
                      parts.id=relocation.part_id
                ORDER BY
                      relocations.date_moved
                DESC
                LIMIT 
                      1
            )
            ,
            parts.location_id
       ) AS locationId,
    locations.name
FROM
    parts
JOIN
    locations ON locations.id=locationId

但是查询无效,MySQL 告诉我 locationId 是一个未知列。我该如何解决这个问题?

表结构

[零件] id | location_id

[搬迁] id | location_id | 日期移动

[地点] id | 姓名

4

1 回答 1

2

如果我理解正确,您正在尝试加入该COALESCE专栏。试试这个:

SELECT a.locationId, locations.name FROM
    (SELECT
        COALESCE(
                    (
                    SELECT
                          relocations.location_id
                    FROM
                          relocations
                    WHERE
                          parts.id=relocation.part_id
                    ORDER BY
                          relocations.date_moved
                    DESC
                    LIMIT 
                          1
                )
                ,
                parts.location_id
           ) AS locationId
    FROM
        parts) a
JOIN locations ON locations.id=a.locationId
于 2012-08-30T15:29:42.960 回答