我有一个WordPress帖子表和一个postmeta表。对于那些不熟悉结构的人来说,他们是:
wp_postmeta
表:
+------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------------------+------+-----+---------+----------------+
| meta_id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| post_id | bigint(20) unsigned | NO | MUL | 0 | |
| meta_key | varchar(255) | YES | MUL | NULL | |
| meta_value | longtext | YES | | NULL | |
+------------+---------------------+------+-----+---------+----------------+
wp_postmeta
的示例数据:
+---------+---------+---------------------+-------------+
| meta_id | post_id | meta_key | meta_value |
+---------+---------+---------------------+-------------+
| 20399 | 267 | youtube_video_id_zh | xdr4lzJ4pYU |
| 20403 | 267 | video_view_count | 3 |
| 21855 | 278 | video_view_count | 13 |
| 21858 | 278 | youtube_video_id_zh | 5yS5cmA4-rg |
| 26042 | 354 | video_view_count | 13 |
| 26138 | 354 | youtube_video_id_zh | iXWMThIohcM |
+---------+---------+---------------------+-------------+
wp_posts
表:( ID是帖子ID)
+------------------------+---------------------+------+-----+----------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------------+---------------------+------+-----+----------+----------------+
| ID | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| (other fields skipped) | | | | | |
+------------------------+---------------------+------+-----+----------+----------------+
每个WordPress帖子都可以在wp_postmeta
中包含多个元行。我需要根据SELECT
的值wp_posts
在ORDER BY
表格上meta_value
进行meta_key
,但仅当video_view_count
为JOIN
时才需要WHERE
我可以获得具有最高/最低视图数的帖子。我无法使用简单的meta_key
,因为{{1}}条件需要检查其他类型的{{1}}。
这是否可以在(我的)SQL中使用?
答案 0 :(得分:1)
首先我们可以从wp_posts加入post meta并选择发布数据。请注意,由于连接,我们使用group by。
SELECT wp_posts.* FROM
wp_posts
LEFT JOIN wp_postmeta ON (wp_posts.id = wp_postmeta.post_id)
GROUP BY wp_posts.id
从这里我们只能加入适当的postmeta并使用它来订购:
SELECT wp_posts.*, wp_postmeta.meta_value AS video_count FROM
wp_posts
LEFT JOIN wp_postmeta ON (wp_posts.id = wp_postmeta.post_id AND wp_postmeta.meta_key = 'video_view_count')
GROUP BY wp_posts.id
ORDER BY wp_postmeta.meta_value
(请注意,如果meta_keys不是每个帖子都重复,则group by实际上并不是必需的)
评论后编辑,在另一个帖子上添加了排除:
SELECT wp_posts.*, wp_postmeta.meta_value AS video_count
FROM wp_posts
INNER JOIN wp_postmeta ex ON (wp_posts.id = ex.post_id AND wp_ex.meta_key = 'video_duration' AND CAST(wp_ex.meta_value AS CHAR) >= '240')
LEFT JOIN wp_postmeta ON (wp_posts.id = wp_postmeta.post_id AND wp_postmeta.meta_key = 'video_view_count')
GROUP BY wp_posts.id
ORDER BY wp_postmeta.meta_value