6

我正在使用WP Data Tables从 SQL DB 创建一个表。在 wordpress 后端中,要使用的示例代码如下所示:

SELECT post_id, post_date
FROM wp_posts
WHERE post_type =  'custom_post_type'
AND post_status =  'publish'

我试图从帖子元中获取自定义字段值。这是我到目前为止...

SELECT post_id, post_date
FROM wp_posts
WHERE post_type =  'custom_post_type'
AND post_status =  'publish'
AND SELECT custom_field_key_1, custom_field_key_2, custom_field_key_3
FROM wp_postmeta
WHERE post_id = post_id

更新:

我发现需要 p.ID 而不是 post_id 并且我需要搜索 meta_key。就像是...

SELECT p.post_title, 
       p.post_date,
       pm.meta_key = 'custom_field_key'
FROM wp_posts p 
INNER JOIN wp_postmeta pm 
ON p.ID = pm.post_id
WHERE p.post_type = 'custom_post_type'
AND p.post_status = 'publish'
4

4 回答 4

4

使用INNER JOIN

SELECT p.post_id, 
       p.post_date, 
       pm.custom_field_key_1, 
       pm.custom_field_key_2, 
       pm.custom_field_key_3
FROM wp_posts p 
   INNER JOIN wp_postmeta pm 
       ON p.post_id = pm.post_id
WHERE p.post_type = 'custom_post_type'
   AND p.post_status = 'publish'
于 2013-03-02T00:21:32.647 回答
0

你可以试试这个。

SELECT p.post_id, p.post_date,
    pm.custom_field_key_1, pm.custom_field_key_2, pm.custom_field_key_3
FROM wp_posts p
JOIN wp_postmeta pm ON p.post_id = pm.post_id
WHERE p.post_type =  'custom_post_type'
AND p.post_status =  'publish'
于 2013-03-02T00:22:18.023 回答
0

假设支持标准 SQL,您将需要这样的东西(未经测试):

SELECT w.post_id, w.post_date, m.custom_field_key_1, m.custom_field_key_2, m.custom_field_key_3
FROM wp_posts w, wp_postmeta m
WHERE post_type =  'custom_post_type' AND post_status =  'publish'
AND w.post.id = m.post.id
于 2013-03-02T00:18:53.367 回答
0

好的,即使您更新了答案。我举了你的例子,我解决了这个问题:

SELECT p.ID, 
       p.post_title, 
       pm.meta_value as 'value1', 
       pma.meta_value as 'value2'

FROM  wp_posts p 
      INNER JOIN wp_postmeta AS pm  ON pm.post_id  = p.ID
      INNER JOIN wp_postmeta AS pma ON pma.post_id = p.ID

WHERE
      pma.meta_key = 'custom_field_key_1' AND
      pm.meta_key = 'custom_field_key_2' AND

      p.post_type = 'your_post_type' AND 
      p.post_status = 'publish'

所以在这里我使用别名AS作为托管在同一个表中的值,仅INNER JOINwp_postmeta而已post_id

参考资料: 多个内连接同一张表

通过这样做,您将获得一个包含帖子和您选择的自定义字段的数组:

array(1) {
    [0]=> object(stdClass)#341 (4) {
          ["ID"]=>    string(1) "1123"
          ["post_title"]=>  string(15) "Your post title"
          ["custom_field_key_1"]=> string(12) "Your value 1 "
          ["custom_field_key_2"]=> string(29) "Your value 2"
}

您可以根据需要添加任意数量的别名和元密钥。希望这有帮助!

于 2015-01-14T21:09:38.000 回答