[英]Performing a Wordpress SQL query with multiple tables
I have a custom field called "points." 我有一个自定义字段,称为“点”。 I want to count up all of the points values for all of the posts which contain that custom field and who also have a specific post title.
我想计算所有包含该自定义字段并且也具有特定帖子标题的帖子的所有点值。
This is what I have so far, but I am having trouble figuring out how to add the parameters since it needs to come from two different tables in the database: 到目前为止,这是我所拥有的,但是由于要从数据库中的两个不同表中获取参数,因此我很难弄清楚如何添加参数:
<?php
// set the meta_key to the appropriate custom field meta key
$meta_key = 'cf_PointValue';
$total_points = $wpdb->get_var( $wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->postmeta
WHERE meta_key = %s
",
$meta_key
) );
echo "<p>Total points: {$total_points}</p>";
?>
I assume there needs to be something added to join it with the other tables. 我认为需要添加一些内容才能将其与其他表连接起来。 What I want it do do is something like this:
我想要它做的是这样的:
<?php
// set the meta_key to the appropriate custom field meta key
$meta_key = 'cf_PointValue';
$total_points = $wpdb->get_var( $wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->postmeta
WHERE meta_key = %s
WHERE post_title = 'name a specific post'
WHERE wp_terms = 'tag1'
",
$meta_key
) );
echo "<p>Total points: {$total_points}</p>";
?>
Thanks in advance for any help you can provide! 预先感谢您提供的任何帮助!
This postmeta thing is a key-value table, and takes some special monkey business to use. 此后元数据是键值表,需要一些特殊的猴子业务才能使用。 It takes a special JOIN operation.
它需要特殊的JOIN操作。 You need a query like this:
您需要这样的查询:
SELECT SUM(m.meta_value) AS points
FROM $wpdb->posts p
JOIN $wpdb->postmeta m ON p.id = m.post_id AND m.meta_key = %s
WHERE p.post_title = 'name a specific post'
AND p.post_status = 'publish'
See the two items in the JOIN of postmeta? 看到postmeta的JOIN中的两项? The first one picks up the appropriate post id, and the second chooses postmeta rows with the correct meta_key value for what you're trying to sum up.
第一个选择适当的帖子ID,第二个选择具有您要总结的内容的meta_key值正确的postmeta行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.