我想选择所有(WordPress)帖子以及最终brand
和brand_id
(均来自同一分类)。如果没有设置品牌,则应始终选择帖子,并将这两个字段设置为NULL
。
此查询几乎可以正常运行,但不包括缺少品牌的帖子:
SELECT
p.ID AS post_id,
p.post_title AS title,
p.post_content AS body,
brand.name AS brand,
brand.term_id AS brand_id,
UNIX_TIMESTAMP(p.post_date) AS date_added
FROM
wp_posts AS p
INNER JOIN wp_term_relationships AS brand_rel
ON brand_rel.object_id = p.ID
INNER JOIN wp_term_taxonomy AS brand_tax
ON brand_tax.term_taxonomy_id = brand_rel.term_taxonomy_id
AND brand_tax.taxonomy = "product_brand"
INNER JOIN wp_terms AS brand
ON brand.term_id = brand_tax.term_id
WHERE
p.post_type = 'product' AND
p.post_status = 'publish'
GROUP BY post_id;
从INNER JOIN
更改为LEFT JOIN
,我收到了所有帖子 - 但他们的品牌(brand
和brand_id
都不是NULL
):< / p>
SELECT
p.ID AS post_id,
p.post_title AS title,
p.post_content AS body,
brand.name AS brand,
brand.term_id AS brand_id,
UNIX_TIMESTAMP(p.post_date) AS date_added
FROM
wp_posts AS p
LEFT JOIN wp_term_relationships AS brand_rel
ON brand_rel.object_id = p.ID
LEFT JOIN wp_term_taxonomy AS brand_tax
ON brand_tax.term_taxonomy_id = brand_rel.term_taxonomy_id
AND brand_tax.taxonomy = "product_brand"
LEFT JOIN wp_terms AS brand
ON brand.term_id = brand_tax.term_id
WHERE
p.post_type = 'product' AND
p.post_status = 'publish'
GROUP BY post_id;
但是,如果我在GROUP BY
期间移除了LEFT JOIN
声明,我似乎可以获得有和没有品牌的所有帖子,但也有很多重复的{{1} }}和brand
字段为brand_id
。
所有帮助表示赞赏。