【问题标题】:Get Post ID with POST METAs in single MySQL query在单个 MySQL 查询中使用 POST META 获取 Post ID
【发布时间】:2023-03-15 05:05:02
【问题描述】:

从 POSTS->ID,我想要 post_type = 'product' 的前 12 个 ID 通过该 ID 关联,我想获取所有 POST META。

我正在使用这个 MySQL 查询,但它不起作用:

SELECT posts.ID, postmeta.meta_key, postmeta.meta_value FROM `wp_u8gwgg_posts` as posts

INNER JOIN wp_u8gwgg_postmeta as postmeta on posts.ID = postmeta.post_id

WHERE 

posts.`post_type` = 'product' AND 
posts.post_status = 'publish'

ORDER BY posts.ID

它在数据中给了我多余的 post_id。:

Post ID | Meta Key       | Meta Value
++++++++++++++++++++++++++++++++++++++
12      | _sku           | 18945236
12      | _price         | 1569.36
12      | _regular_price | 1496.20

我希望结果为:

Post ID | Meta Key                     | Meta Value
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
12      | _sku, _price, _regular_price | 18945236, 1569.36, 1496.20

如果可能,请告诉我解决方案。

如果有任何更好的方法也欢迎。

谢谢

【问题讨论】:

  • GROUP BY + GROUP_CONCAT()
  • 我也试过了,但它给了我In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'simpliav_wp.postmeta.post_id'; this is incompatible with sql_mode=only_full_group_by

标签: mysql wordpress woocommerce posts


【解决方案1】:
SELECT posts.ID, 
       GROUP_CONCAT(postmeta.meta_key ORDER BY posts.ID) meta_keys, 
       GROUP_CONCAT(postmeta.meta_value ORDER BY posts.ID) meta_values 
FROM wp_u8gwgg_posts as posts
INNER JOIN wp_u8gwgg_postmeta as postmeta on posts.ID = postmeta.post_id
WHERE posts.post_type = 'product' 
  AND posts.post_status = 'publish'
GROUP BY posts.ID
ORDER BY posts.ID

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 2017-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多