MYSQL查询CASE返回ELSE

时间:2012-02-16 14:13:45

标签: mysql sql

基本上在以下几行中我有两种情况,即使track_id在driver_id的驱动程序统计信息表中匹配,它也会一直返回ELSES,因为这就是我对查询进行分组的情况。如果我这样做错了,那么我需要的是如果driver_stats表中没有行,那么它从drivers表中获取值,并将增长设置为0.非常感谢任何帮助。

Case s.value When track_id = (SELECT MAX(track_id) FROM driver_stats) Then s.value Else  d.value End AS value,
Case s.growth When track_id = (SELECT MAX(track_id) FROM driver_stats) Then s.growth Else 0 End AS growth,

**//FULL QUERY**
SELECT d.drivers_id, d.drivername, t.code,
Case s.value When track_id = (SELECT MAX(track_id) FROM driver_stats) Then s.value Else  d.value End AS value,
Case s.growth When track_id = (SELECT MAX(track_id) FROM driver_stats) Then s.growth Else 0 End AS growth,
SUM(IF(qual_pos = '1', 1,0)) AS poles,
SUM(IF(race_pos <= '3', 1,0)) AS podiums,
SUM(IF(race_pos = '1', 1,0)) AS victories,
COALESCE(SUM(overtakes),0) AS overtakes,
SUM(Case When s.track_id = (SELECT MAX(track_id) FROM driver_stats) Then points Else 0 End) lastracepoints,
COALESCE(SUM(points),0) AS points
FROM drivers d
Left Join driver_stats s
On s.drivers_id = d.drivers_id
Left Join teams t
On t.team_id = d.team_id
Group By d.drivers_id
ORDER BY d.drivers_id

只是为了解知识,表driver_stats为每个driver_id和每个track_id都有一行。

2 个答案:

答案 0 :(得分:0)

在case和when之间添加值时,应该只添加值,而不是比较。 否则MySQL会将s.value与true进行比较,并且它将始终为false。

您有两种选择:

Case When track_id = (SELECT MAX(track_id) FROM driver_stats) Then s.value Else  d.value End AS value,

Case s.value When (SELECT MAX(track_id) FROM driver_stats) Then s.value Else d.value End AS value,

无论如何,在mySQL中,下一个查询将更容易阅读:

if(s.value=SELECT MAX(track_id) FROM driver_stats, s.value, d.value) as value

答案 1 :(得分:0)

我认为您可以将现有查询简化为以下内容:

SELECT drivers_id, 
       drivername, 
       code,
       coalesce(s_value, d_value) value,
       coalesce(growth, 0) growth,
       SUM(IF(qual_pos = '1', 1,0)) AS poles,
       SUM(IF(race_pos <= '3', 1,0)) AS podiums,
       SUM(IF(race_pos = '1', 1,0)) AS victories,
       COALESCE(SUM(overtakes),0) AS overtakes,
       points lastracepoints,
       COALESCE(SUM(points),0) AS points
from
(SELECT d.drivers_id, d.drivername, t.code, s.value s_value, d.value d_value, s.growth, s.qual_pos, s.race_pos, s.overtakes, s.points
 FROM drivers d
 Left Join driver_stats s On s.drivers_id = d.drivers_id
 Left Join teams t On t.team_id = d.team_id
 ORDER BY d.drivers_id, track_id desc) v
Group By d.drivers_id