带案例的Mysql查询

时间:2016-09-26 13:37:40

标签: php mysql

SELECT *, CASE
    WHEN paydatefinal IS NULL OR paydatefinal = '0000-00-00' THEN paydate
    ELSE    paydatefinal END AS `paydatefinColumn`
FROM
    `ws_crm_comenzi`
WHERE
    `sezonId` = '4'
AND `service_id` = '1'
AND `finished` = '1'
 AND `paydatefinColumn`='2016-09-26'
ORDER BY `paydatefinColumn` DESC

如何在一个案例中制作一个AND(来自一个列(paydatefinColumn),但在表中这个列剂量是否存在

4 个答案:

答案 0 :(得分:2)

您只需在子查询中添加

即可
SELECT * from (SELECT *, CASE WHEN paydatefinal IS NULL OR paydatefinal = '0000-00-00'  
 THEN paydate
ELSE  
 paydatefinal END AS `paydatefinColumn` FROM `ws_crm_comenzi` WHERE `sezonId` = '4' AND `service_id` = '1' AND `finished` = '1')as TEMP  
 where  TEMP.paydatefinColumn='2016-09-26' ORDER BY TEMP.paydatefinColumn DESC;

答案 1 :(得分:1)

由于生成的列相当冗长,并且您无法在where子句中使用生成的列,因此最简单的方法可能是将整个列包装在另一个选择中

SELECT * FROM (

    SELECT *, CASE
        WHEN paydatefinal IS NULL OR paydatefinal = '0000-00-00' THEN paydate
        ELSE    paydatefinal END AS `paydatefinColumn`
    FROM
        `ws_crm_comenzi`
    WHERE
        `sezonId` = '4'
    AND `service_id` = '1'
    AND `finished` = '1'
     AND `paydatefinColumn`='2016-09-26'
    ORDER BY `paydatefinColumn` DESC)

 AS A WHERE paydatefinColumn = whatever

答案 2 :(得分:0)

您应该以这种方式重复代码

  SELECT *, CASE
      WHEN paydatefinal IS NULL OR paydatefinal = '0000-00-00' THEN paydate
      ELSE    paydatefinal END AS `paydatefinColumn`
  FROM
      `ws_crm_comenzi`
  WHERE
      `sezonId` = '4'
  AND `service_id` = '1'
  AND `finished` = '1'
   AND (CASE
      WHEN paydatefinal IS NULL OR paydatefinal = '0000-00-00' THEN paydate
      ELSE    paydatefinal END  ) = str_toDate('2016-09-26', '%Y-%m-%d')
  ORDER BY `paydatefinColumn` DESC

答案 3 :(得分:0)

您需要在where子句

中重复CASE语句
SELECT *, CASE
    WHEN paydatefinal IS NULL OR paydatefinal = '0000-00-00' THEN paydate
    ELSE    paydatefinal END AS `paydatefinColumn`
FROM
    `ws_crm_comenzi`
WHERE
    `sezonId` = '4'
AND `service_id` = '1'
AND `finished` = '1'
AND
 CASE
    WHEN paydatefinal IS NULL OR paydatefinal = '0000-00-00' THEN paydate
    ELSE    paydatefinal END='2016-09-26'
ORDER BY `paydatefinColumn` DESC