基于2列过滤MySQL语句(meta_key和meta_value)

时间:2013-04-15 23:10:23

标签: mysql wordpress

我有以下SQL语句来计算基于wp_postmeta,wp_post和wp_user表的几个字段。我需要的是仅包含结果,其中所有帖子都有meta_key ='key1'和meta_value> ='1.5'。我试着在下面的声明中但它没有过滤,仍然显示每条记录。

非常感谢任何帮助!

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='key1' AND pm.meta_value >='1.5' THEN 1 ELSE 0 END) > 0
ORDER BY Balance DESC

1 个答案:

答案 0 :(得分:1)

我会多次加入post meta表。这应该利用索引来更快地返回查询。如果两个用户具有相同的u.ID,您可能希望按display_name进行分组。如果您更改数据库前缀,使用$wpdb->posts$wpdb->postmeta是一个好主意,这对安全性来说是个好主意。

注意,这是未经测试的。

SELECT 
    display_name user,
    IFNULL(SUM(won.meta_value),0) won,
    IFNULL(SUM(lost.meta_value),0) lost,
    IFNULL(COUNT(odd.meta_value),0) total,
    IFNULL(ROUND(AVG(odd.meta_value),2),0) avg_odd,
    IFNULL(ROUND(AVG(bet.meta_value),2),0) avg_bet,
    IFNULL(ROUND(SUM(balance.meta_value),2),0) balance
FROM {$wpdb->posts} p
JOIN {$wpdb->users} u 
    ON p.post_author = u.ID
JOIN {$wpdb->postmeta} odd 
    ON p.ID = odd.post_id AND odd.meta_key = 'odd'
LEFT JOIN {$wpdb->postmeta} won 
    ON p.ID = won.post_id AND won.meta_key = 'status' AND won.meta_value = 'won'
LEFT JOIN {$wpdb->postmeta} lost 
    ON p.ID = lost.post_id AND lost.meta_key = 'status' AND lost.meta_value = 'lost'
LEFT JOIN {$wpdb->postmeta} bet 
    ON p.ID = bet.post_id AND bet.meta_key = 'bet'
LEFT JOIN {$wpdb->postmeta} balance 
    ON p.ID = balance.post_id AND balance.meta_key = 'balance'
WHERE 
    MONTH(p.post_date) = MONTH(CURRENT_DATE) 
    AND p.post_status = 'publish'
GROUP BY u.ID
HAVING SUM(odd.meta_value) >= 1.5
ORDER BY balance DESC