简体   繁体   中英

Filtering SQL Query with if conditions

I have the following SQL query to retrieve all the coupon code from the database but I want to filter it such a way that I need coupon codes for certain store name. The actual syntax that retrieves all the coupon records is

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

And, it retrieves like 在此处输入图片说明

I tried giving the value field_name`='storename', `field_value`='Ceylon Inn', null and its displaying the storename as 0 and 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

在此处输入图片说明

Can anyone help me how to retrieve the list as per storename? Thanks.

If you only want one store, then use a having clause:

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;

Also, don't use single quotes for identifiers. Only use single quotes for string and date constants.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM