WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] SQL to get cat ids of posts (5 posts)

  1. deko
    Member
    Posted 3 years ago #

    I trying to get cat ids for posts with SQL outside the loop. The below SQL works, but I need a LEFT JOIN... not sure where...
    SELECT terms.term_id, terms.name, term_taxonomy.description, term_taxonomy.count, term_taxonomy.term_taxonomy_id, posts.ID, term_relationships.object_id, term_relationships.term_taxonomy_id FROM terms INNER JOIN (term_taxonomy INNER JOIN (term_relationships INNER JOIN posts ON posts.ID = term_relationships.object_id) ON term_relationships.term_taxonomy_id = term_relationships.term_taxonomy_id) ON terms.term_id = term_taxonomy.term_id
    suggestions?

  2. deko
    Member
    Posted 3 years ago #

    Actually, that query DOES work. All it needs to a WHERE clause. Still, it's ugly. Is there a better way?

    Remember, NOT in the loop...

    What if I grab the post ID like this: $postid = $_Get["p"]

    I want to discover what the corresponding category ID is for that $postid.

    Do I have to run a query with 3 joins to find it?

  3. deko
    Member
    Posted 3 years ago #

    Yes, I do 3 joins...

    $thispost = $_GET["p"];

    "SELECT term_relationships.term_taxonomy_id FROM terms INNER JOIN (term_taxonomy INNER JOIN (term_relationships INNER JOIN posts ON posts.ID = term_relationships.object_id) ON term_relationships.term_taxonomy_id = term_relationships.term_taxonomy_id) ON terms.term_id = term_taxonomy.term_id WHERE (posts.ID = ".$thispost.") LIMIT 1;"

    isn't normalization great?

  4. deko
    Member
    Posted 3 years ago #

    actually, 1 join shd do it...

    $thispost = $_GET["p"];
    SELECT term_relationships.term_taxonomy_id FROM term_relationships INNER JOIN posts ON posts.ID = term_relationships.object_id WHERE (posts.ID = ".$thispost.");

    assuming the post is in only one category

  5. deko
    Member
    Posted 3 years ago #

    corrected...

    $thispost = $_GET["p"];
    SELECT term_taxonomy.term_id FROM term_taxonomy INNER JOIN term_relationships ON term_taxonomy.term_taxonomy_id = term_relationships.term_taxonomy_id INNER JOIN posts ON posts.ID = term_relationships.object_id WHERE (posts.ID = ".$thispost.");

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags