SQL:以下查询有什么问题(由WordPress WP_QUERY生成,订购价格)

时间:2016-11-23 作者:Blackbam

嘿,我有以下SQL查询,它是由WP\\u Query numeric meta Query生成的:

SELECT SQL_CALC_FOUND_ROWS wp_postmeta.meta_value FROM wp_posts 
INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) 
INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) 
WHERE 1=1 
AND ( wp_postmeta.meta_key = \'price\' 
AND ( mt1.meta_key = \'price\' 
AND CAST(mt1.meta_value AS SIGNED) BETWEEN \'0\' AND \'9999\' ) ) 
AND wp_posts.post_type = \'product\' 
AND (wp_posts.post_status = \'publish\' OR wp_posts.post_status = \'private\') 
GROUP BY wp_posts.ID ORDER BY CAST(wp_postmeta.meta_value AS SIGNED) DESC LIMIT 0, 15
WordPress查询(如果有帮助的话)是这样生成的,应该是正确的:

array(6) {
  ["orderby"]=>
  array(1) {
    ["price"]=>
    string(4) "DESC"
  }
  ["meta_query"]=>
  array(3) {
    ["relation"]=>
    string(3) "AND"
    ["sortprimary_clause"]=>
    array(3) {
      ["key"]=>
      string(17) "price"
      ["compare"]=>
      string(6) "EXISTS"
      ["type"]=>
      string(7) "numeric"
    }
    [0]=>
    array(4) {
      ["key"]=>
      string(17) "price"
      ["value"]=>
      array(2) {
        [0]=>
        float(0)
        [1]=>
        float(9999)
      }
      ["compare"]=>
      string(7) "BETWEEN"
      ["type"]=>
      string(7) "numeric"
    }
  }
  ["tax_query"]=>
  array(1) {
    ["relation"]=>
    string(3) "AND"
  }
  ["post_type"]=>
  string(7) "product"
  ["posts_per_page"]=>
  int(15)
  ["paged"]=>
  string(1) "1"
}
结果如下:

Query result

正如您所看到的,SQL对值的排序基本上是正确的,但仅限于价格的整数大小。小数分隔符似乎被完全忽略了。如何更改SQL以正确使用浮点数。这是WordPress的问题还是我可以更改WP\\U查询以使其正确处理浮点数?

编辑:我发现了问题!ORDER BY CAST(wp_postmeta.meta_value AS SIGNED) 应该是ORDER BY CAST(wp_postmeta.meta_value AS DECIMAL(M,3)).

所以问题是:How can I change WP_Query to use a decimal value for comparison instead of Integer?

1 个回复
SO网友:Blackbam

已解决。编辑之后就很容易了。允许在meta\\u查询中使用type=>“decimal(x,x)”。最大精度为十进制(65,30)。

https://dev.mysql.com/doc/refman/5.7/en/precision-math-decimal-characteristics.html

array(6) {
  ["orderby"]=>
  array(2) {
    ["uss_product_price"]=>
    string(4) "DESC"
    ["title"]=>
    string(3) "ASC"
  }
  ["meta_query"]=>
  array(3) {
    ["relation"]=>
    string(3) "AND"
    ["sortprimary_clause"]=>
    array(3) {
      ["key"]=>
      string(17) "price"
      ["compare"]=>
      string(6) "EXISTS"
      ["type"]=>
      string(13) "decimal(30,5)"
    }
    [0]=>
    array(4) {
      ["key"]=>
      string(17) "price"
      ["value"]=>
      array(2) {
        [0]=>
        float(0)
        [1]=>
        float(9999)
      }
      ["compare"]=>
      string(7) "BETWEEN"
      ["type"]=>
      string(7) "decimal(30,5)"
    }
  }
  ["tax_query"]=>
  array(1) {
    ["relation"]=>
    string(3) "AND"
  }
  ["post_type"]=>
  string(7) "product"
  ["posts_per_page"]=>
  int(15)
  ["paged"]=>
  string(1) "2"
}