mySQL get information from multiple tables in one query

后端 未结 3 1558
生来不讨喜
生来不讨喜 2021-01-06 05:23

I\'m terribly new to SQL, and cannot seem to get the desired information out, after trying a few different google searches, and reading through some SQL tutorials.

I

相关标签:
3条回答
  • 2021-01-06 05:50

    You will need to use a JOIN statement to retrieve fields from multiple tables. 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'
    

    Also, you're table structure looks to have a little redundancy.

    0 讨论(0)
  • 2021-01-06 05:57
    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';
    

    I think you need some way to associate a row in Comments to the correct row in Activity. Right now if two people comment on a given Task on the same day, you don't know whose comment is whose. I'd recommend that you give each row in Activity a unique key, and then reference that from the Comments table.

    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;
    

    Then you can make associations so the query returns more accurate results:

    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';
    

    Make sure to use TYPE=InnoDB in MySQL because the default storage engine MyISAM doesn't support foreign key references.

    0 讨论(0)
  • 2021-01-06 06:12

    Are you planning on joining the tables based on the date? So you will only have 1 change per day?

    0 讨论(0)
提交回复
热议问题