1

这是我的查询。所以我需要从仅在组件 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'
)
4

1 回答 1

0

好的。所以我认为你的意思是你有三个自定义字段的帖子;“组件”、“组件年”和“预算”。当组件 = 1 和组件年 = 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'
);
于 2013-11-12T19:01:31.683 回答