开发者

Fetch last item in a category that fits specific criteria

开发者 https://www.devze.com 2022-12-28 18:27 出处:网络
Let\'s assume I have a database with two tables: categories and articles. Every article belongs to a category.

Let's assume I have a database with two tables: categories and articles. Every article belongs to a category.

Now, let's assume I want to fetch the l开发者_运维知识库atest article of each category that fits a specific criteria (read: the article does). If it weren't for that extra criteria, I could just add a column called last_article_id or something similar to the categories table - even though that wouldn't be properly normalized.

How can I do this though? I assume there's something using GROUP BY and HAVING?


Try with:

   SELECT * 
     FROM categories AS c
LEFT JOIN (SELECT * FROM articles ORDER BY id DESC) AS a
       ON c.id = a.id_category
      AND /criterias about joining/
    WHERE /more criterias/
 GROUP BY c.id


If you provide us with the Tables schemas, we could be a little more specific, but you could try something like (12.2.9.6. EXISTS and NOT EXISTS, SELECT Syntax for LIMIT)

SELECT  *
FROM    articles a
WHERE   EXISTS  (   
                    SELECT  1 
                    FROM    articles 
                    where   category_id = a.category_id
                    AND     <YourCriteria Here>
                    ORDER BY    <Order Required : ID DESC, LastDate DESC or something?
                    LIMIT 1
                )


Assuming the id's in the articles table represent always increasing numbers, this should work. Using the id is not semantically correct IMHO, you should actually use a time/date tamp field if one is available.

SELECT * FROM articles WHERE article_id IN
  (
    SELECT 
      MAX(article_id) 
    FROM
      articles 
    WHERE [your filters here]
    GROUP BY 
      category_id
  )
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号