mySQL在一个查询中从多个表中获取信息

时间:2008-10-23 19:31:58

标签: mysql database

我对SQL非常陌生,在尝试了一些不同的谷歌搜索并阅读了一些SQL教程之后,似乎无法获得所需的信息。

我认为它涉及某种类型的连接,但不能直接使用它们。

给出以下样本表:

表1(活动每次对任务进行更改时都会更新,每天可以多次):

ID  Who     What        When
001 John    Created 2008-10-01<br>
001 Bill    Closed  2008-10-02<br>
001 John    Updated 2008-10-03<br>
002 Bill    Created 2008-10-04<br>
002 John    Updated 2008-10-05<br>
002 Bill    Closed  2008-10-06<br>

表2(任务 - 这是主要任务跟踪表):

ID  Created Status
001 2008-10-01  Closed
002 2008-10-04  Closed

表3(评论):

ID  When    Comment<br
001 2008-10-01  "I'm creating a new task"
001 2008-10-02  "I have completed the task"
001 2008-10-03  "Nice job"
002 2008-10-04  "I'm creating a second task"
002 2008-10-05  "This task looks too easy"
002 2008-10-06  "I have completed this easy task"

我会用什么SQL(mySQL,如果它有什么不同)查询来找出谁已经关闭的任务?

结果如下:

Who What    ID  When    Comment
Bill Updated 002 2008-10-03 "Nice job"

意味着Bill在关闭后更改了任务002,并添加了评论“Nice Job”

非常感谢任何帮助。

提前致谢。

3 个答案:

答案 0 :(得分:7)

SELECT a1.Who, a1.What, a1.ID, c.When, c.Comment
FROM Activity AS a1
  JOIN Activity AS a2 ON (a1.ID = a2.ID AND a1.When > a2.When)
  JOIN Comments AS c ON (a1.ID = c.ID AND a.When = c.When);
WHERE a2.What = 'Closed';

我认为您需要某种方法将Comments中的行与Activity中的正确行相关联。现在,如果有两个人在同一天评论给定的任务,你不知道谁的评论是谁。我建议你给Activity中的每一行赋一个唯一的密钥,然后从Comments表中引用它。

CREATE TABLE Tasks (
  Task_ID      INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  Created      DATE NOT NULL,
  Status       VARCHAR(10)
) TYPE=InnoDB;

CREATE TABLE Activity (
  Activity_ID  INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  Task_ID      INT NOT NULL REFERENCES Tasks,
  Who          VARCHAR(10) NOT NULL,
  What         VARCHAR(10) NOT NULL,
  When         DATE NOT NULL
) TYPE=InnoDB;

CREATE TABLE Comments (
  Comment_ID   INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  Activity_ID  INT NOT NULL REFERENCES Activity,
  Who          VARCHAR(10) NOT NULL,
  When         DATE NOT NULL,
  Comment      VARCHAR(100) NOT NULL
) TYPE=InnoDB;

然后您可以建立关联,以便查询返回更准确的结果:

SELECT c.Who, a1.What, a1.Task_ID, c.When, c.Comment
FROM Activity AS a1
  JOIN Activity AS a2 ON (a1.Task_ID = a2.Task_ID AND a1.When > a2.When)
  JOIN Comments AS c ON (a1.Activity_ID = c.Activity_ID);
WHERE a2.What = 'Closed';

确保在MySQL中使用TYPE=InnoDB,因为默认存储引擎MyISAM不支持外键引用。

答案 1 :(得分:2)

您需要使用JOIN语句从多个表中检索字段。 http://www.w3schools.com/Sql/sql_join.asp

SELECT Activity.Who, Activity.What, Comments.When, Comments.Comment FROM Activity JOIN Comments ON Activity.ID = Comments.ID JOIN Tasks ON Comments.ID = Tasks.ID WHERE Tasks.Status = 'Closed'

此外,您的表结构看起来有点冗余。

答案 2 :(得分:0)

您是否计划根据日期加入表格?那你每天只会换一次吗?