mysql - Wordpress 高级 SQL - 连接和计数

标签 mysql wordpress select count

事情是这样的
我使用 Wordpress 类别表并有 2 个主要类别。第一个称为“location”,另一个称为“subject”。这两个类别都有自己的子类别。

在我的示例中,我们有“location”类别 17 和“subject”类别 3。

这就是我想要做的
我只想选择同时显示我的类别 17 和 3 的数据。

这段代码目前有效

SELECT term_id, post_title, post_name, ID, object_id, post_status
FROM wp_posts AS wpost
INNER JOIN wp_term_relationships
   ON wpost.ID = wp_term_relationships.object_id

INNER JOIN wp_term_taxonomy
   ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id AND wp_term_taxonomy.taxonomy = 'category'

WHERE wp_term_taxonomy.term_id IN (17, 3)
   AND post_status = 'publish'

问题
类别 17 和 3 都存在于同一列中。如果帖子出现在两个类别中,上面的代码会列出两次 ID。

有没有办法计算结果中相等的 ID? 如果 ID 存在两次,请从该 ID 中选择帖子

最佳答案

这将只选择每个帖子一次,如果它存在于两个类别中:

SELECT  post_title, post_name, post_status
FROM    wp_posts AS wpost
WHERE   post_status = 'publish'
        AND EXISTS (
        SELECT   1
        FROM     wp_term_relationships
        INNER JOIN
                 wp_term_taxonomy
        ON       wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
                 AND wp_term_taxonomy.taxonomy = 'category'
                 AND wp_term_taxonomy.term_id IN (17, 3)
        WHERE    wp_term_relationships.object_id = wpost.ID
        LIMIT 1, 1
        )

关于mysql - Wordpress 高级 SQL - 连接和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/939929/

相关文章:

mysql - 编写具有多个搜索功能的查询?

excel - 创建一个表,显示另一个工作表中选定的行

php - 如何在 Laravel 5.x 中将多个集合合并为一个集合?

mysql - 获取日期时间从/到特定时间之间的平均计数

wordpress - 使用 WooCommerce 设置高级 Paypal 后禁用 CSC 字段

php - 将产品数据添加到 WooCommerce 管理订单预览

php - MySQL UNION 不返回任何结果

mysql - 如何编写 Laravel 查询来对重复记录进行分组

mysql - 如何使用mysql通过单独的字符串从表中检索最大值或最高值

wordpress - 如何修复 'Some files are not writable by WordPress' 错误,管理员无法更改网站