Hello all, I have a query I am using to retrieve all posts of a specific type, status and date. The query is dynamic in that one of these things doesn’t need to be present and the query will omit them.
I would like to extend this query to also allow the search to be refined by the category to which the post belongs but this will involve a join as there are 2-3 tables involved.
POSTS table that contains the post, it’s status and type.
RELATIONSHIPS which contains the id of the post and the id of the category
CATEGORIES which contains category details.
I’m not 100% that I need to join it to categories since I have the category_id from $_GET and the category_id in RELATIONSHIPS, but either way I am struggling to think how to create an appropriate join where I can include all of the other search specifics and the join. At it’s most specific, my query is something like this:
SELECT * FROM posts WHERE post_type = 'post' AND post_status = 'draft' AND YEAR(FROM_UNIXTIME(date_created))=2011 AND MONTH(FROM_UNIXTIME(date_created))=12 LIMIT 10
I think the query I want would be something like:
SELECT * FROM p.posts
LEFT OUTER JOIN relationships AS r
ON r.category_id = ".$_GET['category_id']. "
LEFT OUTER JOIN categories AS c
ON c.category_id = r.category_id
WHERE p.post_type = 'post' AND p.post_status = 'draft'
AND YEAR(FROM_UNIXTIME(p.date_created))=2011 AND MONTH(FROM_UNIXTIME(p.date_created))=12 LIMIT 10"
Which does seem to be working, but it’s also returning 5000 results when I only have a few hundred posts, it duplicates them all in massive quantities, so I’m doing something wrong. I tried the following, adding a “p.” identifier for the post table:
SELECT COUNT( * ) AS num_rows
FROM posts AS p
LEFT OUTER JOIN relationships AS r ON r.category_id =1
LEFT OUTER JOIN categories AS c ON c.category_id = r.category_id
WHERE p.post_type = 'post'
AND p.post_status = 'draft'
AND YEAR( FROM_UNIXTIME( date_created ) ) =2011
AND MONTH( FROM_UNIXTIME( date_created ) ) =11
But this just fails because of a syntax error.