|
|
|
|
|
by xi
5105 days ago
|
|
That means #1 is totally relational (as an aside, you don't need ORDER BY or LIMIT for it either). I would love to see it. Yes, you can do it in SQL, but I'd say it's not easy at all without ORDER BY and LIMIT or windowing functions and I don't know if you can do it in Tutorial D. For the reference, #1 is: Show the blog post with the largest number of comments. If more than one exist, pick the latest. The schema is: post(id integer, created timestamp)
comment(id integer, post_id integer)
See CJ Date's excellent discussion on ORDER(BY)I read it and the book as well, but I wouldn't call it excellent. What I read there is a reluctant admission of failure to incorporate an important operation to his query model. I see no attempt to analyze why it doesn't work or adapt the query model to make ORDER a regular operation. |
|
And we can make up any operator we want as long as it uses a primitive, so (to save typing I created a view, but you could copy-pasta). I added a "Title" to post because otherwise you could skip it entirely and just use the comment table twice, but where's the fun in that?
<pre> CREATE VIEW counts AS ( select count() AS comment_count, post_id from comment group by post_id )
SELECT id, title, comment_count FROM post p INNER JOIN counts AS c1 ON p.id = c1.post_id WHERE NOT EXISTS( SELECT FROM counts AS c2 WHERE c2.post_id != p.id AND c2.comment_count > c1.comment_count ) </pre>