1

如何在 UNION 结果中创建条件?

解释:我正在做一个 UNION 搜索,它工作正常。问题是在最后一个 WHERE 上创建一个新过滤器。如图所示,它没有被应用。

代码:

SELECT * FROM 
(
        SELECT
            locacoes.id as id,
            locacoes.chave as chave,
            'L' AS tipo,
            locacoes.codigo as codigo,
            locacoes.localRetirada as localRetirada,
            locacoes.clienteID as clienteID,
            locacoes.dataSaida as dataSaida,
            locacoes.dataChegada as dataChegada,
            locacoes.veiculo as veiculo,
            locacoes.situacao as situacao,
            locacoes.historico AS historico,
            veiculos.placa as placa,
            veiculos.marca as marca,
            veiculos.modelo as modelo
        FROM
            locacoes
            LEFT JOIN veiculos ON veiculos.id = veiculo
        WHERE
            locacoes.chave = '1323122'
    UNION
        SELECT
            contratos.id AS id,
            contratos.chave AS chave,
            'C' AS tipo,
            contratos.codigo AS codigo,
            contratos.localRetirada AS localRetirada,
            contratos.clienteID AS clienteID,
            contratos.dataIni AS dataSaida,
            contratos.dataFim AS dataChegada,
            contratos.veiculo as veiculo,
            contratos.status AS situacao,
            contratos.historico AS historico,
            veiculos.placa as placa,
            veiculos.marca as marca,
            veiculos.modelo as modelo
        FROM
            contratos
            LEFT JOIN veiculos ON veiculos.id = veiculo
        WHERE
            contratos.chave = '1323122' 

) AS derived_table

    WHERE
        dataSaida <= '2022-02-07 13:51:00' AND dataChegada >= '2022-02-07 13:51:00' 
        AND placa = 'GEC7I31'
        OR (`historico` IS NULL) ORDER BY historico asc

我哪里错了?

4

0 回答 0