在 MySQL 数据库中,我有两个表 'VEHICLE' 和 'VEHICLE_CLASS',如下所示:
VEHICLE
-------------------------------------------
VEHICLE_ID | VEHICLE_CLASS_ID | STATUS
-------------------------------------------
vehicle_001 | vehicle_class_001 | 0
vehicle_002 | vehicle_class_002 | 1
vehicle_003 | vehicle_class_003 | 2
vehicle_004 | vehicle_class_001 | 0
vehicle_005 | vehicle_class_002 | 2
vehicle_006 | vehicle_class_001 | 0
vehicle_007 | NULL | 1
----------------------------------------------
VEHICLE_CLASS
------------------------------------------
VEHICLE_CLASS_ID | VEHICLE_CLASS_NAME
-----------------------------------------
vehicle_class_001 | ABC
vehicle_class_002 | BCD
vehicle_class_003 | EFG
vehicle_class_004 | XYZ
vehicle_class_005 | PQR
vehicle_class_006 | STU
---------------------------------------
- 共有三种状态 0 = 已启动,1 = 进行中,2 = 已完成
我需要一个查询来获取结果行,如下所示:
-----------------------------------------------------------------------
VEHICLE_CLASS_NAME | COMPLETED_ VEHICLES | NOT_COMPLETED_ VEHICLES
---------------------------------------------------------------------------
ABC | |vehicle_001, vehicle_004, vehicle_006
BCD | vehicle_005 |vehicle_002
EFG | vehicle_003 |
- 如果 Status=2 则完成,否则未完成。
这是我写的查询,但它没有给我正确的行。
SELECT
veh.VEHICLE_CLASS_ID,
vehclass.VEHICLE_CLASS_NAME,
IF(STATUS=2, GROUP_CONCAT(`VEHICLE_ID`),'') COMPLETED_ VEHICLES,
IF(STATUS<2,GROUP_CONCAT(`VEHICLE_ID`),'') NOT_COMPLETED_ VEHICLES
FROM
VEHICLE veh
LEFT JOIN VEHICLE_CLASS vehclass
on veh.VEHICLE_CLASS_ID = vehclass.VEHICLE_CLASS_ID
GROUP BY
veh.VEHICLE_CLASS_ID
having
veh.VEHICLE_CLASS_ID is not null;
请帮助我,我怎样才能得到结果行。谢谢你。