用于从2个表中检索数据的SQL查询语法

时间:2014-07-01 15:18:35

标签: mysql

我在Mysql中有两个表:authorsarticles

我的作者为他们每个人都有几篇文章。

我需要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

1 个答案:

答案 0 :(得分:0)

如果您只想包括在前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