mysql - 组合来自 MYSQL 的选择值,然后细化落在某个范围内的值

标签 mysql wordpress woocommerce

我有一个 WordPress 数据库,wp_postmeta 表中包含 meta_key 和 meta_value 列。我目前正在尝试选择元键为 _sale_price 且元值 > 0 的所有行:

SELECT * FROM `ra_postmeta` WHERE `meta_key` = '_sale_price' AND `meta_value` > 0

这很好用。不过我想进一步完善这些结果。我还需要使用另外两个 meta_key_sale_price_dates_from_sale_price_dates_to。我只想包含今天的 strototime 日期的行,例如1406649975 属于 _sale_price_dates_from_sale_price_dates_to 范围。这是因为有些产品的 sale_price > 0,但计划稍后开始销售,我不希望这些产品在结果中返回。例如。

_sale_price_dates_from >= 1406649975 AND _sale_price_dates_to <= 1406649975

但是我对 SQL 的了解不够深,无法做到这一点。

是不是类似:

SELECT * FROM `ra_postmeta` 
WHERE (`meta_key` = '_sale_price' AND `meta_value` > 0) 
AND (`meta_key` = '_sale_price_dates_to' AND ( `meta_value` >= 1406649975 OR `meta_value`=null)) 
AND (`meta_key` = '_sale_price_dates_from' AND ( `meta_value` <= 1406649975 OR `meta_value`=null))

(但这返回零行)

谢谢

最佳答案

这是一个典型的困难,人们遇到(否则灵活)EAV model .

您需要为每种类型的元数据自连接一次表:

SELECT sale_price.post_id

-- first, let's check for the sale price
FROM ra_postmeta AS sale_price

-- then we need to check the "dates to"
-- the LEFT JOIN, instead of (INNER) JOIN, makes the query return all rows from sale_price
-- even if there is no match on "dates_to" (which equates to your "OR meta_value=NULL") clause
LEFT JOIN ra_postmeta AS dates_to
    ON dates_to.meta_id = sale_price.meta_id        -- this is the real JOIN condition
    AND dates_to.meta_key = '_sale_price_dates_to'  -- this selects only meta-data related to "dates to"
    AND dates_to.meta_value >= 1406649975           -- condition on this meta-data

-- then we need to check the "dates from", we take the exact same approach as with "dates to"
LEFT JOIN ra_postmeta AS dates_from
    ON dates_from.meta_id = sale_price.meta_id
    AND dates_from.meta_key = '_sale_price_dates_from'
    AND dates_from.meta_value <= 1406649975

-- finally, the conditions on the first table (in the FROM clause)
WHERE
    sale_price.meta_key = '_sale_price'
    AND sale_price.meta_value > 0

关于mysql - 组合来自 MYSQL 的选择值,然后细化落在某个范围内的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25020735/

相关文章:

wordpress - 选择不同的文件夹来覆盖 woocommerce 模板

mysql - 如何在 laravel 5 中对关系列使用 'having' 和分页

php - 无法在 Codeigniter 中查看表单页面

mysql - 更新 MySQL 中的缓存计数

php - 使用 WP_User_Query 时如何忽略搜索字符串大小写?

php - 更改 wordpress 主题的帖子循环设计

linux - 在 WordPress 中上传的文件不可见/不可用

javascript - 如果显示自定义字段,则显示/隐藏按钮

php - 在 WooCommerce 中以编程方式更新客户的账单信息

php - MySQL COUNT(*) 返回空结果集