Answer the question
In order to leave comments, you need to log in
How to limit query selection with join tables on one table in SQL
There are two tables with a one-to-many relationship: the articles table with articles and the comments table with the corresponding comments. The usual selection of them is made as follows (the latest articles and the first comments on them are selected):
SELECT
articles.title,
articles.date,
comments.author,
comments.text
FROM
articles
INNER JOIN comments ON comments.article = articles.id
ORDER BY
articles.id DESC,
comments.id ASC
Answer the question
In order to leave comments, you need to log in
1. Instead of the usual join, we do a slightly unusual one:
SELECT *
FROM comments as c
INNER JOIN (SELECT * FROM articles LIMIT 10) as a
ON a.id = c.aticle_id
2. No way with one query.
3. One request does not.
2 and 3 is done by simply selecting articles with or without limit, and then fetching comments for each article with or without limit.
For 2 and 3 you can do this:
SELECT t1.title, t1.date, t1.author, t1.text
FROM
(SELECT articles.title, articles.date, comments.author, comments.text, articles.id as aid, comments.id as cid, DENSE_RANK() OVER ( ORDER BY articles.id DESC) as article_row, row_number () over (partition by articles.id order by comments.id) as comment_row
FROM articles INNER JOIN comments ON articles.id = comments.article ) AS t1
WHERE t1.article_row<=2 and t1.comment_row<=5
ORDER BY t1.aid DESC, t1.cid
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question