如何从同一列从WordPress自定义字段数据库中检索总和

时间:2013-11-12 15:36:04

标签: php mysql database wordpress custom-fields

这是我的查询。所以我需要从预算元键的值中检索总和,这些值仅在组件1和2009年。我该如何做。提前致谢

SELECT SUM(
b.meta_value)
, b.meta_key
FROM wp_posts AS p, wp_postmeta AS b, wp_postmeta AS m, wp_postmeta AS n
WHERE (
p.ID = b.post_id
)
AND (
b.meta_key =  'budget'
)
AND (
m.meta_key =  'component'
AND m.meta_value =  '1'
)
AND (
n.meta_key =  'component-year'
AND n.meta_value =  '2009'
)

1 个答案:

答案 0 :(得分:0)

行。所以我认为你说的是​​你有三个自定义字段的帖子; “组件”,“组件年”和“预算”。当component = 1和component-year = 2009时,您试图获得“预算”的总值。如果这是正确的,那么这是有效的 - 它不是最有效的,但它工作正常。

SELECT SUM(wp_postmeta.meta_value) AS total
FROM wp_posts 
LEFT JOIN wp_postmeta ON (
    wp_posts.ID = wp_postmeta.post_id
    AND
    wp_postmeta.meta_key = 'budget'
)

# get all the posts with a custom field of "component" of "1"
WHERE wp_posts.ID IN (
    SELECT post_id
    FROM wp_postmeta
    WHERE meta_key =  'component'
    AND meta_value =  '1'
)

# and all the posts with a custom field of "component-year" of "2009"
AND wp_posts.ID IN (
    SELECT post_id
    FROM wp_postmeta
    WHERE meta_key =  'component-year'
    AND meta_value =  '2009'
);