MYSQL查询连接表

时间:2013-03-19 17:48:58

标签: mysql sql wordpress

这是我对WP数据库的查询。

$letters = $wpdb->get_col(
"SELECT DISTINCT LEFT(post_title,1) AS first_letter FROM $wpdb->posts
WHERE post_type = '$post_type' AND post_status = 'publish'
ORDER BY first_letter ASC"
);

这是一个婴儿名称数据库,我想制作一个小部件来分隔男性/女性,所以我需要像上面那样进行查询,但是只获得一些帖子只有一些postmeta,下面是我正在寻找的关键和价值。

Key - spin2

价值 - 男性

如何将其添加到查询中,因为它位于不同的表中?

谢谢!

1 个答案:

答案 0 :(得分:1)

您只需使用INNER JOIN

SELECT DISTINCT LEFT(posts.post_title,1) AS first_letter 
FROM $wpdb->posts AS posts 
    INNER JOIN $wpdb->postmeta AS meta
        ON posts.ID = meta.post_id
WHERE posts.post_type = '$post_type' 
    AND posts.post_status = 'publish'
    AND meta.meta_key = 'spin2'
    AND meta.meta_value = 'Male'
ORDER BY first_letter ASC