简体   繁体   中英

SQL joining wordpress tables

I am struggling with an SQL query to join 3 tables to return specific results.

Anyone familiar with wordpress may be able to assist as I am using word press to power post interactions with the db behind the scenes but am building a custom UI. The three tables are: -

posts  (**ID**, post_title, post_content, post_modified_gmt)
term_relationships (**object_id**, term_taxonomy)
terms (**term_id**, name, slug)

I have got as far as..

 SELECT posts.post_title FROM posts
 INNER JOIN term_relationships
 ON posts.ID = term_relationships.object_id

Which returns a list of all the post titles that have a matching ID number in term_relationships. However term names are in the table 'terms' and the ID's don't match the other two tables. In the terms table the term_id refers to the name of the term, eg

term_id = 2, name = blog

Basically I am trying to achieve a query whereby if I set the term_id = 2 it returns all the rows from the table posts that have the term relationship to blog, meaning the query returns all blog posts and I am completely lost!

Can anyone give me a few pointers? my mind is boggled.

I managed to achieve the result I was looking for with the following query, but would still appreciate some pointers should anyone stumble upon this and have the inclination :)

         SELECT * FROM posts
            INNER JOIN term_relationships
            ON posts.ID = term_relationships.object_id
         WHERE term_relationships.term_taxonomy_id = 2 
            AND posts.post_type = 'post' 
            AND posts.post_status = 'publish'
         ORDER BY posts.post_modified_gmt ASC
         LIMIT 0,5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM