Mysql:如何在查询中使用CASE

时间:2011-05-30 12:03:23

标签: mysql sql mysql-error-1064

我有以下查询:

SELECT
    t.id as tid
  , t.uid tuid
  , t.bid_type
  , tt.type as type
  , t.bid_category
  , tc.type as category
  , t.name, if(t.description IS NULL
  , '-', t.description) as description
  , date_format(t.sdate, '%m-%d-%Y %H:%i') as tsdate
  , date_format(t.endate, '%m-%d-%Y %H:%i') as tendate
  , date_format(t.adate, '%m-%d-%Y %H:%i:%s') as tadate
  , if(t.edate IS NULL, '-', date_format(t.edate, '%m-%d-%Y %H:%i:%s')) as tedate
  , t.status
  , tq.id as tqid
  , tq.bid
  , if(tq.amount IS NULL, '-', tq.amount) as amount
  , if(tq.hand IS NULL, '-', tq.hand) as hand
  , if(tq.game = 0 OR tq.game IS NULL, '-', tg.type) as game
  , if(tq.stake = 0 OR tq.stake IS NULL, '-', ts.type) as stak
  , if(tq.player = 0 OR tq.player IS NULL, '-', tq.player) as player
  , if(tq.tourney IS NULL, '-', tq.tourney) as tourney
  , if(tq.propbet, 'Prop bet', '-') as propbet
  , if(tq.race, 'Race', '-') as race
  , tq.status as tqstatus 
  , CASE 
    WHEN tq.amount IS NOT NULL THEN tq.amount 
    WHEN tq.hand IS NOT NULL THEN tq.hand 
    WHEN tq.tourney IS NOT NULL THEN tq.tourney 
    WHEN tq.propbet IS NOT NULL THEN 'Prop bet' 
    WHEN tq.race IS NOT NULL THEN 'Race' 
    END CASE as bidData
FROM (bid t)
JOIN bid_quote tq ON tq.bid = t.id
JOIN bid_type tt ON tt.id = t.bid_type
                AND tt.pid = 0
JOIN bid_type tc ON tc.id = t.bid_category
JOIN bid_game tg ON tg.id = tq.game
JOIN bid_stake ts ON ts.id = tq.stake

上面提到的查询给出了错误。有人可以指导我如何纠正它,以便CASE应该在查询中工作。这是错误:

  

SQL错误(1064):您的SQL语法中有错误;查看与您的MySQL服务器版本对应的手册,以便在'CASE作为bidData FROM(bid t)附近使用正确的语法JOIN bid_quote tq ON tq.bid = t.id在第9行加入bid_'

2 个答案:

答案 0 :(得分:7)

删除CASE中的END CASE字样。在一个查询中,您只能使用END结束一个案例,而不是存储过程。

PS:你知道你也可以在查询中使用输入和缩进,对吧? ; - )

答案 1 :(得分:2)

存储过程有一种情况,查询有一种情况。

http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#operator_case