MySQL Query WHERE - >如果

时间:2014-05-08 10:24:18

标签: mysql if-statement where-clause

希望有人能帮助我,

我试图通过IF操作连接MySQL语句中的WHERE参数,但我不知道如何处理它......

SELECT  k.EventId AS Id
    , ws.Name AS Name
    , dauer AS Dauer
    , kat.Name AS Kurztyp
    , doz.Name AS Dozent        
    , DATE_FORMAT(k.Begin, '%Y-%m-%d') AS Begin
    , COUNT(an.EventId) AS Teilnehmer
FROM kalender AS k
        LEFT JOIN workshop AS ws        
            ON (k.WorkshopId = ws.Id)
        LEFT JOIN angemeldet AS an      
            ON (k.EventId = an.EventId)
        LEFT JOIN dozent AS doz         
            ON (k.Dozent = doz.Id)
        LEFT JOIN ws_kategorie as kat   
            ON ((ws.Kategorie = kat.Id) or (ws.Kategorie2 = kat.Id))
        INNER JOIN bezahlvariante AS bezvar
                ON (an.bezahlvariante_idbezahlvariante = bezvar.idbezahlvariante)
    WHERE kat.Name LIKE '%security%'
        AND k.Begin > '2014-04-01'
        AND k.aktiv = '1'

---------------->

        AND bezvar.TN_Anzahl_phys = '1'

< -----------------这应该是这样的:IF(COUNT(an.EventId)> 0)
                        比如bezvar.TN_Anzahl_phys =' 1'
ELSE bezvar.TN_Anzahl_phys IN(1,2)

            GROUP BY k.EventId;

如何在MySQL中使用这样的IF操作?

1 个答案:

答案 0 :(得分:2)

您可以将case-when用作

GROUP BY k.EventId
having
case 
  when COUNT(an.EventId)>0 then bezvar.TN_Anzahl_phys = '1'
  else
   bezvar.TN_Anzahl_phys IN (1,2)
END