我有一个表有许多类别,然后是一个反对这些值的值 - 我需要尝试从该表中提取(仅使用MySQL)值不为零的类别的名称和值本身
例如:
awk -F, '{print gsub("\"","\"\"",$2)}' OFS=, vehicle_file.txt
在上面我需要得到类似的东西:
ID car phone gym pension
1 200 15 12 20
2 0 15 12 25
3 0 0 0 30
4 0 0 0 0
5 150 20 12 0
以下查询返回正确的ID和值,但它也返回零值(ID 4除外),而不是类别名称:
1 Car 200
1 Phone 15
1 Gym 12
1 Pension 20
2 Phone 15
2 Gym 12
2 Pension 25
3 Pension 30
5 Car 150
5 Phone 20
5 Gym 12
我可以在PHP中执行此操作但是可以在MySQL中执行此操作吗?
答案 0 :(得分:3)
您可以使用UNION ALL
执行此操作:
SELECT id, car AS col
FROM benefits
WHERE car!=0
UNION ALL
SELECT id, phone AS col
FROM benefits
WHERE phone!=0
UNION ALL
SELECT id, gym AS col
FROM benefits
WHERE gym!=0
UNION ALL
SELECT id, pension AS col
FROM benefits
WHERE pension !=0
答案 1 :(得分:2)
我认为实现此目标的最简单方法是使用UNION ALL
,每列一次:
SELECT id,'Car' as val , car
FROM benefits WHERE car <> 0
UNION ALL
SELECT id,'Phone' as val , phone
FROM benefits WHERE phone <> 0
UNION ALL
SELECT id,'Car' as val , car
FROM benefits WHERE car <> 0
UNION ALL
SELECT id,'Gym' as val , Gym
FROM benefits WHERE Gym<> 0
UNION ALL
SELECT id,'Pension' as val , Pension
FROM benefits WHERE Pension <> 0
order by id