PHP查询未返回正确值

时间:2019-10-29 11:20:17

标签: mysql

我有一个这样的表维可利

-------------------------------------------------------
| ID  |   Modello |   Targa             |  Marca     |
-------------------------------------------------------
| 1   |   IVECO   |   XA123WE            |  GRANDX    |
-------------------------------------------------------
| 2   |   IVECO   |   CF556XD            |  TOURS     |
-------------------------------------------------------
| 3   |   FIAT    |   AS332ZZ            |  Punto     |
-------------------------------------------------------

对于每辆车,我都有一个或多个 revisioni_veicolo (日期较大的那一列是我需要根据今天的日期检查保险是否仍然有效)

-------------------------------------------------------------------
| ID  |   veicoli_ID   |   DataScadenzaRevisione | EsitoPositivo  |
-------------------------------------------------------------------
| 1   |   1            | 2019-07-01             |        1
------------------------------------------------------------------
| 2   |   1            | 2020-10-01             |        0
-------------------------------------------------------------------
| 3   |   2            | 2019-11-25             |        1
-------------------------------------------------------------------
| 4   |   2            | 2018-10-20             |        1
-------------------------------------------------------------------

感谢这里的另一篇文章,我实现了我的代码,以仅搜索StatoUltimaRevisione = 1(StatoUltimaRevisione是veicoli_ID分组的EsitoPositivo的值,并且仅与组内的MAX DataScadenzaRevisione相关)...但与我的查询有关:

SELECT DISTINCT veicoli.ID, veicoli.Modello, veicoli.Marca,
                t1.MaxDataScadenzaRevisione, t3.StatoUltimaRevisione,
                CASE WHEN t1.MaxDataScadenzaRevisione IS NULL THEN 1 ELSE 0 END AS RevisioneScaduta,
                CASE WHEN t2.veicoli_ID IS NULL THEN 0 ELSE 1 END AS RevisionePresente
FROM veicoli LEFT JOIN ( SELECT veicoli_ID, MAX(DataScadenzaRevisione) AS MaxDataScadenzaRevisione FROM revisioni_veicolo GROUP BY veicoli_ID) t1 on t1.veicoli_ID = veicoli.ID AND t1.MaxDataScadenzaRevisione >= date(NOW())
LEFT JOIN ( SELECT veicoli_ID, MAX(DataScadenzaRevisione) AS MaxDataScadenzaRevisione2, EsitoPositivo AS StatoUltimaRevisione FROM revisioni_veicolo GROUP BY veicoli_ID) t3 ON t3.veicoli_ID = veicoli.ID
LEFT JOIN ( SELECT veicoli_ID FROM revisioni_veicolo ) t2 ON t2.veicoli_ID = veicoli.ID
HAVING StatoUltimaRevisione = 1

我总是在ID = 1的结果veicolo上显示。为什么?

array( ....
  'ID' => string '1'
  'Modello' => string 'IVECO'
  'Marca' => string 'GRANDX'
  'MaxDataScadenzaRevisione' => string '2020-10-01'
  'StatoUltimaRevisione' => string '1'   <---------------WRONG!!!!!!!
  'RevisioneScaduta' => string '0'
  'RevisionePresente' => string '1'

添加小提琴2:ID为26的http://sqlfiddle.com/#!9/e2e43c/5 veicolo不正确...显示ID 114代替143,StatoUltimaRevisione不正确

0 个答案:

没有答案