我在wp_post和wp_post_meta WP数据库中有数据:一个包含“工作坊”的唯一条目,第二个包含与每个研讨会相关的元数据。表格如下:
WP_POST TABLE
| post ID | post title | post type | post content etc.
|---------------------------------------------------------
| 1 | workshop 1 | workshop | cooking with apples
| 2 | workshop 2 | workshop | cooking with pears
| 3 | workshop 3 | workshop | cooking with bananas
WP META TABLE
| post ID | meta key | meta value | etc.
|---------------------------------------------------------
| 1 | summary | apples | ..
| 1 | date | 20100518 | ..
| 1 | duration | 1 hour | ..
| 2 | summary | pears | ..
| 2 | date | 20100623 | ..
| 2 | duration | 1/2 day | ..
| 3 | summary | bananas | ..
| 3 | date | 20101111 | ..
| 3 | duration | all day | ..
我一直在玩查询。
SELECT post_title, post_date, post_type, meta_key, meta_value, post_content
FROM wp_posts as post INNER JOIN wp_postmeta as meta ON post.ID = meta.post_id
WHERE post.post_status = "publish" AND post.post_type = "workshop"
此查询给了我一张看起来像这样的表。
| post ID | post title | post type | meta key | meta value | etc.
|--------------------------------------------------------------------------------
| 1 | workshop 1 | workshop | summary | apples | ..
| 1 | workshop 1 | workshop | date | 20100518 | ..
| 1 | workshop 1 | workshop | duration | 1 hour | ..
| 2 | workshop 2 | workshop | summary | pears | ..
| 2 | workshop 2 | workshop | date | 20100623 | ..
| 2 | workshop 2 | workshop | duration | 1/2 day | ..
| 3 | workshop 3 | workshop | summary | bananas | ..
| 3 | workshop 3 | workshop | date | 20101111 | ..
| 3 | workshop 3 | workshop | duration | all day | ..
我需要做的是对元键值“ date”进行排序,但是我不确定执行此操作的最佳方法。我可以按“元键”日期的“元值”排序吗?
我思考我需要创建一个这样的表才能实现,但是不知道该怎么做,即使这是必需的方法。
| post ID | post title | summary | date | duration | etc.
|--------------------------------------------------------------
| 1 | workshop 1 | apples | 20100518 | 1 hour
| 2 | workshop 2 | pears | 20100623 | 1/2 day
| 3 | workshop 3 | bananas | 20101111 | all day
答案 0 :(得分:0)
您可以仅使用join
对日期进行排序:
select p.*, d.meta_value as date
from wp_post p join
wp_meta d
on d.post_id = p.post_id and d.meta_key = 'date'
order by d.meta_value;
答案 1 :(得分:0)
您可以使用汇总功能在每个帖子的不同列中显示元数据信息,例如
SELECT p.post_title,
p.post_date,
p.post_type,
p.post_content,
MAX(CASE WHEN m.meta_key = 'summary' THEN m.meta_value ELSE NULL END) summary,
MAX(CASE WHEN m.meta_key = 'duration' THEN m.meta_value ELSE NULL END) duration,
MAX(CASE WHEN m.meta_key = 'date' THEN m.meta_value ELSE NULL END) `date`
FROM wp_posts as p
INNER JOIN wp_postmeta as m ON p.ID = m.post_id
WHERE p.post_type = "workshop" AND p.post_status = "publish"
GROUP BY p.post_title,
p.post_date,
p.post_type,
p.post_content
ORDER BY STR_TO_DATE(MAX(CASE WHEN m.meta_key = 'date' THEN m.meta_value ELSE NULL END), '%Y%m%d')
要使用元数据值对数据集进行排序,您首先需要使用STR_TO_DATE