根据特定的meta_key和meta_value过滤postmeta

时间:2013-04-15 16:08:11

标签: mysql wordpress

我有以下SQL语句来计算基于3个Wordpress表的几个字段。我需要的是仅包含meta_key ='odd'和meta_value> ='1.5'的结果。我尝试了WHERE语句,但它不起作用,因为此查询中的大多数结果显示为Null。

非常感谢任何帮助!

SELECT (display_name) AS 'user',
    SUM(Case When meta_key = 'status' Then meta_value = 'won' else Null End) AS 'Won',
    SUM(Case When meta_key = 'status' Then meta_value = 'lost' else Null End) AS 'Lost',
    COUNT(Case When meta_key = 'odd' Then meta_value else Null End) AS 'Total',
    ROUND (AVG(Case When meta_key = 'odd' Then meta_value else Null End), 2) AS 'Avg odd',
    ROUND (AVG(Case When meta_key = 'bet' Then meta_value else Null End), 2) AS 'Avg bet',
    ROUND (SUM(Case When meta_key = 'balance' Then meta_value else Null End), 2) AS 'Balance'
FROM wp_postmeta pm
INNER JOIN wp_posts p ON pm.post_id = p.ID 
INNER JOIN wp_users u ON p.post_author = u.ID
WHERE Month(post_date) = MONTH(CURRENT_DATE) AND p.post_status='publish' AND pm.meta_key='odd' AND pm.met.value >='1.5'
GROUP BY (display_name)
ORDER BY Balance DESC

1 个答案:

答案 0 :(得分:1)

您需要将其移至having子句:

SELECT (display_name) AS 'user',
    SUM(Case When meta_key = 'status' Then meta_value = 'won' else Null End) AS 'Won',
    SUM(Case When meta_key = 'status' Then meta_value = 'lost' else Null End) AS 'Lost',
    COUNT(Case When meta_key = 'odd' Then meta_value else Null End) AS 'Total',
    ROUND (AVG(Case When meta_key = 'odd' Then meta_value else Null End), 2) AS 'Avg odd',
    ROUND (AVG(Case When meta_key = 'bet' Then meta_value else Null End), 2) AS 'Avg bet',
    ROUND (SUM(Case When meta_key = 'balance' Then meta_value else Null End), 2) AS 'Balance'
FROM wp_postmeta pm
INNER JOIN wp_posts p ON pm.post_id = p.ID 
INNER JOIN wp_users u ON p.post_author = u.ID
WHERE Month(post_date) = MONTH(CURRENT_DATE) AND p.post_status='publish' 
GROUP BY (display_name)
having SUM(case when pm.meta_key='odd' AND pm.meta_value >='1.5' then 1 else 0 end) > 0
ORDER BY Balance DESC

这确定每个display_name是否存在这样的行。