尝试根据不同表中的日期从表中返回日期时,不确定以下WHERE语句是否有效

时间:2017-01-30 21:25:54

标签: php mysql date

我已经编写了一个sql查询,并且我已经对它进行了测试,我得出的结论是WHERE语句给了我一些问题。

方案: 我有一个包含日期列表的表。让我们称这个表为表格。

我有第二个表格,其中包含表格2列,“开始日期”“结束日期”

我想要做的是,根据“开始日期”“结束日期”之间的日期过滤表A中的日期,其中包含日期列表。

例如,如果“开始日期” - 01/01/2017和“结束日期”是01/02/2017,那么我想要返回日期在表A中包含所有日期的开始日期结束日期之间。

这是我写的SQL查询:

$query = "SELECT ec.ElecEnergy, ec.GasEnergy, ec.Date, c.ElecCharge, c.GasCharge, ec.User, st.AmountSetElec, st.AmountSetGas,
st.StartDate, st.EndDate, st.TargetElecCharge, st.TargetGasCharge, ua.Username
FROM energyconsumption ec INNER JOIN
useraccount ua
ON ec.User = ua.id
INNER JOIN
energytarget st
ON st.customerID = ua.id INNER JOIN
Charge c
ON ec.ChargeID = c.id
INNER JOIN
energytarget st ON
st.energyID = ec.id
WHERE ec.Date = ec.Date >= st.StartDate AND ec.Date <= st.EndDate
GROUP BY  ec.ElecEnergy, ec.GasEnergy,   c.ElecCharge, c.GasCharge, st.AmountSetElec, st.AmountSetGas, st.StartDate, st.EndDate, ua.Username ";

问题 如何根据表B中“开始日期”和“结束日期”之间的日期编写一个WHERE语句,用于过滤表A中的日期。

谢谢!

编辑:

我尝试使用BETWEEN语句来解析语句,这就是我所做的:

$query = "SELECT ec.ElecEnergy, ec.GasEnergy, ec.Date, c.ElecCharge, c.GasCharge, ec.User, st.AmountSetElec, st.AmountSetGas,
st.StartDate, st.EndDate, st.TargetElecCharge, st.TargetGasCharge, ua.Username
FROM energyconsumption ec INNER JOIN
useraccount ua
ON ec.User = ua.id
INNER JOIN
energytarget st
ON st.customerID = ua.id INNER JOIN
Charge c
ON ec.ChargeID = c.id
INNER JOIN
energytarget st ON
st.energyID = ec.id
WHERE ec.Date BETWEEN ec.Date >= st.StartDate AND ec.Date <= st.EndDate
GROUP BY  ec.ElecEnergy, ec.GasEnergy,   c.ElecCharge, c.GasCharge, st.AmountSetElec, st.AmountSetGas, st.StartDate, st.EndDate, ua.Username ";

此外,声明“

可能存在问题
INNER JOIN
    energytarget st ON
    st.energyID = ec.id"

位于WHERE语句

之上

1 个答案:

答案 0 :(得分:0)

您的查询在JOIN子句中有错误:

有两个具有相同别名的join子句:

    INNER JOIN energytarget st ON st.customerID = ua.id 
    INNER JOIN energytarget st ON st.energyID = ec.id

SELECT ec.ElecEnergy, ec.GasEnergy, ec.Date, c.ElecCharge, c.GasCharge, 
       ec.User, st.AmountSetElec, st.AmountSetGas, st.StartDate, 
       st.EndDate, st.TargetElecCharge, st.TargetGasCharge, ua.Username
FROM energyconsumption ec 
     INNER JOIN useraccount ua ON ec.User = ua.id
     INNER JOIN energytarget st ON st.customerID = ua.id 
     INNER JOIN Charge c ON ec.ChargeID = c.id
     INNER JOIN energytarget st ON st.energyID = ec.id
WHERE 
    ec.Date = ec.Date >= st.StartDate AND ec.Date <= st.EndDate
GROUP BY ec.ElecEnergy, ec.GasEnergy, c.ElecCharge, 
         c.GasCharge, st.AmountSetElec, st.AmountSetGas, 
         st.StartDate, st.EndDate, ua.Username