使用if条件过滤SQL查询

时间:2014-06-29 15:27:38

标签: mysql sql

我有以下SQL查询从数据库中检索所有优惠券代码,但我想过滤它,以便我需要某些商店名称的优惠券代码。检索所有优惠券记录的实际语法是

SELECT `submit_time` AS 'Submitted', max(if(`field_name`='storename', `field_value`, null )) AS 'storename', max(if(`field_name`='coupon-date', `field_value`, null )) AS 'coupon-date', max(if(`field_name`='start-time', `field_value`, null )) AS 'start-time', max(if(`field_name`='end-time', `field_value`, null )) AS 'end-time', max(if(`field_name`='num-coupons', `field_value`, null )) AS 'num-coupons' FROM `wp_cf7dbplugin_submits` WHERE `form_name` = 'Add Coupon' GROUP BY `submit_time` ORDER BY `submit_time` DESC LIMIT 0,100

并且,它检索类似enter image description here

我尝试给出值field_name`='storename', `field_value`='Ceylon Inn', null,并将商店名称显示为0和1。

SELECT `submit_time` AS 'Submitted', max(if(`field_name`='storename', `field_value`='Ceylon Inn', null )) AS 'storename', max(if(`field_name`='coupon-date', `field_value`, null )) AS 'coupon-date', max(if(`field_name`='start-time', `field_value`, null )) AS 'start-time', max(if(`field_name`='end-time', `field_value`, null )) AS 'end-time', max(if(`field_name`='num-coupons', `field_value`, null )) AS 'num-coupons' FROM `wp_cf7dbplugin_submits` WHERE `form_name` = 'Add Coupon' GROUP BY `submit_time` ORDER BY `submit_time` DESC LIMIT 0,100

enter image description here

任何人都可以帮我如何按照商店名称检索列表吗?感谢。

1 个答案:

答案 0 :(得分:1)

如果您只想要一个商店,那么请使用having子句:

SELECT `submit_time` AS Submitted,
        max(if(`field_name`='storename', `field_value`, null )) AS storename, 
        max(if(`field_name`='coupon-date', `field_value`, null )) AS `coupon-date`, 
        max(if(`field_name`='start-time', `field_value`, null )) AS `start-time`,
        max(if(`field_name`='end-time', `field_value`, null )) AS `end-time`,
        max(if(`field_name`='num-coupons', `field_value`, null )) AS `num-coupons`
FROM `wp_cf7dbplugin_submits`
WHERE `form_name` = 'Add Coupon'
GROUP BY `submit_time`
HAVING storename = 'storename'
ORDER BY `submit_time` DESC
LIMIT 0,100;

此外,请勿对标识符使用单引号。仅对字符串和日期常量使用单引号。