选择带有别名和连接的SQL查询

时间:2012-05-06 01:17:07

标签: sql database wordpress group-by

我正在进行为期2天的查询,但我不知道如何制作它。

基本上我正在使用多个连接进行查询:

我的查询:

SELECT wp_posts.ID, wp_posts.post_title, wp_posts.post_content, wp_posts.post_type,     
wp_term_taxonomy.taxonomy, wp_terms.name
FROM wp_term_relationships, wp_term_taxonomy, wp_terms, wp_posts
WHERE wp_term_relationships.object_id =80
AND wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
AND wp_term_taxonomy.term_taxonomy_id = wp_terms.term_id
AND wp_term_relationships.object_id = wp_posts.ID

这就是她所展示的(在顶部),以及我想要展示的内容(底部)

http://tinyurl.com/cnjmuxs

非常感谢你的帮助

1 个答案:

答案 0 :(得分:2)

也许其他人有更清洁的方法来做到这一点,但以下情况应该有效:

SELECT wp_posts.ID, wp_posts.post_title, wp_posts.post_content, wp_posts.post_type, 
    MAX(
        CASE WHEN wp_term_taxonomy.taxonomy = 'reference' THEN wp_terms.name ELSE '' END 
    ) AS reference,
    MAX(
        CASE WHEN wp_term_taxonomy.taxonomy = 'chinesename' THEN wp_terms.name ELSE '' END 
    ) AS chinesename,
    MAX(
        CASE WHEN wp_term_taxonomy.taxonomy = 'price' THEN wp_terms.name ELSE '' END 
    ) AS price
FROM wp_term_relationships, wp_term_taxonomy, wp_terms, wp_posts
WHERE wp_term_relationships.object_id =80
    AND wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
    AND wp_term_taxonomy.term_taxonomy_id = wp_terms.term_id
    AND wp_term_relationships.object_id = wp_posts.ID
GROUP BY wp_posts.ID, wp_posts.post_title, wp_posts.post_content, wp_posts.post_type