我在Mysql中有2个表:authors
和articles
。
我的作者每人都有几篇文章。
我需要使用此查询的结果进行sql查询:检索3个按年龄排序的作者,并包含属于他们每个人的所有文章。
在我的例子中
ID FIRSTNAME LASTNAME AGE AUTHORID TITLE PRICE
6 Salido Gomes 90 6 All 3 1
6 Salido Gomes 90 6 All 3 33
6 Salido Gomes 90 6 All 3 3
5 Vitora Mantora 45 5 Total 3 99
5 Vitora Mantora 45 5 Total 3 33
5 Vitora Mantora 45 5 Total 3 12
3 Joe Smith 43 3 Python 5
3 Joe Smith 43 3 Python 2 22
3 Joe Smith 43 3 Python 3 44
3 Joe Smith 43 3 Python 4 12
3 Joe Smith 43 3 Python 5 67
http://sqlfiddle.com/#!2/718c4/1
我用
select * from authors join articles on authors.id = articles.authorId
join (select authors.id from authors order by age DESC limit 3) as t
on t.id = authors.id
结果错误
ID FIRSTNAME LASTNAME AGE AUTHORID TITLE PRICE
6 Salido Gomes 90 6 All 3 1
6 Salido Gomes 90 6 All 3 33
6 Salido Gomes 90 6 All 3 3
如果您只想包括在前3名最老的作者中写过任何文章的作者,请尝试在子查询中将作者与文章进行连接以获得3名最老的作者,然后使用DISTINCT来消除重复:
SELECT *
FROM
(
SELECT DISTINCT authors.id, authors.firstname, authors.lastname, authors.age
FROM authors
JOIN articles
ON authors.id = articles.authorId
ORDER BY authors.age
DESC
LIMIT 3
) author_sub
JOIN articles
ON author_sub.id = articles.authorId
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句