[英]SQL query syntax to retrieve data from 2 tables
我在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.