Mysql和case语句不起作用

时间:2013-11-11 16:08:56

标签: mysql sql

/*-------------temp table--------------*/
CREATE TEMPORARY TABLE IF NOT EXISTS bowlpick.tempschedule AS

(SELECT * FROM bowlpick.schedule

where season = (select max(year) from bowlpick.season));
/*-------------temp table--------------*/

set @g1= (select winner from bowlpick.tempschedule where game =1);

select date,name, @g1,bowl1 Pick,comf1

,case 
    when bowl1 =  @g1 then  comf1 
    when bowl1 <> @g1 then -comf1 
else '0' end pts

from bowlpick.picks
where year(date) = (select max(year) from bowlpick.season)
order by bowl1 desc limit 5



<--------------------Table----------------->
  name      @g1            Pick       comf1 pts
Player 1    Boise State     Washington  7   -7
Player 2    Boise State     Boise State 30  -30
Player 3    Boise State     Boise State 21  -21
Player 4    Boise State     Boise State 27  -27
Player 5    Boise State     Boise State 15  -15

为什么这不起作用?最后四个应该是正数,而不是负数。 好像变量(@ g1)在'CASE'部分不起作用。它在'选择'部分时正常工作。 如果我对获胜者(博伊西州)进行硬编码,它就能正常运行。变量在case语句中不起作用吗?

1 个答案:

答案 0 :(得分:0)

不确定为什么要使用临时表,你可以在一个查询中执行此操作,请参阅以下示例以了解某个地方,另一件事我注意到这个案例是返回两个case语句和一个字符串的数字对于其他人。不仅如此,case语句还有2个WHEN语句,这些语句涵盖了所有基本,这意味着“0”从未被选中过。

SELECT 
    bowlpick.picks.date
    ,bowlpick.picks.name
    ,bowlpick.tempschedule.winner
    ,bowlpick.picks.bowl1 Pick
    ,bowlpick.picks.comf1
    ,CASE 
        WHEN bowlpick.picks.bowl1 =  bowlpick.tempschedule.winner  THEN bowlpick.picks.comf1 
        WHEN bowlpick.picks.bowl1 <> bowlpick.tempschedule.winner  THEN -bowlpick.picks.comf1 
        ELSE 0
    END pts
FROM 
    bowlpick.picks
    LEFT JOIN bowlpick.tempschedule ON year(bowlpick.picks.date) = bowlpick.tempschedule.season 
WHERE 
    bowlpick.tempschedule.game =1
ORDER BY 
    bowl1 DESC
LIMIT 5

以下是一项额外的工作,删除了对临时表的需求(链接和分组需要更好的定义,但使用不完整的模式,这是我能做的最好的)

SELECT 
    p.Date
    ,p.Name
    ,s.Winner
    ,p.Bowl1 Pick
    ,p.Comf1
    ,CASE 
        WHEN p.Bowl1 =  s.Winner  THEN p.Comf1 
        WHEN p.Bowl1 <> s.Winner  THEN -p.Comf1 
        ELSE 0
    END pts
FROM 
    picks p
    LEFT JOIN schedule s ON YEAR(p.Date) = s.Season 
WHERE 
    s.game = 1
GROUP BY 
    s.Season, p.Date
HAVING
    s.Season = MAX(s.Season)
ORDER BY 
    p.Bowl1 DESC
LIMIT 5

他是我SQL Fiddle曾经这样做的