需要将2个查询合并为1个

时间:2019-12-12 17:00:24

标签: mysql sql

我想将这2个查询合并为1个。有人可以帮助我吗?

查询1:

SELECT
    Date_Consommation AS Date_Consommation, 
    Odometre AS Odometre,   
    IDProduits AS IDProduits,   
    IDZ_Consommations_Provenances AS IDZ_Consommations_Provenances, 
    IDEmployes AS IDEmployes,   
    IDFournisseurs AS IDFournisseurs
FROM 
    Consommations
WHERE IDVehicules = 3140
AND Date_Consommation <= '20191114'
ORDER BY Date_Consommation DESC, Odometre DESC
LIMIT 1

查询2:

SELECT
    Odometre AS maxOdo
FROM
    Consommations
WHERE IDVehicules = 3140
AND Date_Consommation >= '20191114'
ORDER BY Date_Consommation, Odometre
LIMIT 1

例如,这是数据以及我想要的结果: click here for image

The result I want is:
Date_Consommation = 2019-11-12
Odometre = 221698
IDProduits = 342412 
IDZ_Cons... = 16
IDEmployes = 10 
IDFournisseurs = 3
maxOdo = 222354

3 个答案:

答案 0 :(得分:0)

如果您的数据库允许CTE,那将是一种方法。您需要将IDvehicules添加到每个查询的输出中,然后将两个查询结合到IDvehicules上。另外,由于将输出限制为一行,因此不需要order by子句。

答案 1 :(得分:0)

我认为可以对同一张表使用交叉联接(或内部联接ON C1.IDVehicules = C2.IDVehicules)并选择所需的数据,这是SQL,但未经任何测试。

SELECT
    C1.Date_Consommation AS Date_Consommation, 
    C1.Odometre AS Odometre,   
    C1.IDProduits AS IDProduits,   
    C1.IDZ_Consommations_Provenances AS IDZ_Consommations_Provenances, 
    C1.IDEmployes AS IDEmployes,   
    C1.IDFournisseurs AS IDFournisseurs
    C2.Odometre AS maxOdo
FROM 
    Consommations C1
    CROSS JOIN Consommations C2 
WHERE C1.IDVehicules = 3140 AND C2.IDVehicules = 3140
    AND C1.Date_Consommation <= '20191114' AND C2.Date_Consommation >= '20191114'
ORDER BY C1.Date_Consommation DESC, C1.Odometre DESC, C2.Date_Consommation, C2.Odometre
LIMIT 1

答案 2 :(得分:0)

在您的所有帮助下,这就是我如何获得想要的东西!

SELECT
    bloc1.Date_Consommation,
    bloc1.Odometre,
    bloc1.IDProduits,
    bloc1.IDZ_Consommations_Provenances,
    bloc1.IDEmployes,
    bloc1.IDFournisseurs,
    bloc2.maxOdo
FROM
    (SELECT
        Date_Consommation,
        Odometre,
        IDProduits,
        IDZ_Consommations_Provenances,
        IDEmployes,
        IDFournisseurs
    FROM Consommations
    WHERE IDVehicules = 3140
    AND Date_Consommation <= '20191114'
    ) bloc1,

    (SELECT MAX(Odometre) AS maxOdo
    FROM Consommations
    WHERE IDVehicules = 3140
    AND Date_Consommation >= '20191114'
    ) bloc2

ORDER BY Date_Consommation DESC, Odometre DESC
LIMIT 1