在函数中使用子查询

时间:2015-11-11 14:15:49

标签: mysql

好吧,我是一个新的mysql我坚持以下场景:

    SELECT 
    h.machine_id,
    h.pin_no,
    h.created_at,
    (SELECT 
            created_at
        FROM
            history AS h1
        WHERE
            h1.created_at > h.created_at
                AND h1.machine_id = h.machine_id
                AND h1.pin_no = h.pin_no
                AND h1.state = 1
        LIMIT 1) AS ended_at,

TIMEDIFF(ended_at,created_at)已过去

FROM
    history AS h
WHERE
    h.state = 0

我想在函数中使用子查询的值,比如datediff,我该如何实现呢?我会使用cte,如果它是mssql:)

1 个答案:

答案 0 :(得分:1)

您只是将子查询嵌入函数中作为参数。顺便说一下,这与子查询没有关系,而是因为你不能在同一个SELECT列表中重复使用表达式。

SELECT 
    h.machine_id,
    h.pin_no,
    h.created_at,
    (SELECT 
            created_at
        FROM
            history AS h1
        WHERE
            h1.created_at > h.created_at
                AND h1.machine_id = h.machine_id
                AND h1.pin_no = h.pin_no
                AND h1.state = 1
        LIMIT 1) AS ended_at,
   TIMEDIFF((SELECT 
            created_at
        FROM
            history AS h1
        WHERE
            h1.created_at > h.created_at
                AND h1.machine_id = h.machine_id
                AND h1.pin_no = h.pin_no
                AND h1.state = 1
        LIMIT 1),created_at) as elapsed
FROM
    history AS h
WHERE
    h.state = 0

如果您真的无法使用子查询两次,则可以使用派生表表达式来计算子查询,然后可以在外部查询中多次使用该子查询。

SELECT
    calculations.machine_id,
    calculations.pin_no,
    calculations.created_at,
    calculations.ended_at,
    TIMEDIFF(calculations.ended_at, calculations.created_at) AS elapsed
FROM (
    SELECT 
        h.machine_id,
        h.pin_no,
        h.created_at,
        (SELECT 
                created_at
            FROM
                history AS h1
            WHERE
                h1.created_at > h.created_at
                    AND h1.machine_id = h.machine_id
                    AND h1.pin_no = h.pin_no
                    AND h1.state = 1
            LIMIT 1) AS ended_at
    FROM
        history AS h
    WHERE
        h.state = 0
) AS calculations