【问题标题】:Joined 3 tables, not outputting all results from third table?加入 3 个表,不输出第三个表的所有结果?
【发布时间】:2016-03-04 19:41:53
【问题描述】:

我有三张桌子:

Student - UPN, Name, Year, House

Seclusion_Status - ID, Arrived, FTE, Rebuild, DateTimeAdded, Staff, Student_UPN (fk), Comment

Period_Rating - ID, Slot_ID, Rating, Date, Seclusion_ID (fk)

每个学生在 Seclusion_Status 表中可以有很多条目,然后在 Period_rating 表中也有很多条目,这些条目以 Seclusion_ID 链接到 Seclusion_status 表

我正在运行以下查询以根据日期从 Seclusion_Status 返回一条记录,然后是 Period_rating 表中与 Seclusion_status 记录相关的所有记录。

$sql="SELECT * FROM Seclusion_Status 
      INNER JOIN Students ON Seclusion_Status.Student_UPN=Students.UPN 
      JOIN Period_Rating ON Seclusion_Status.ID=period_rating.Seclusion_ID
      WHERE period_rating.Date = '$start'
      GROUP BY period_rating.Seclusion_ID 
      ORDER BY Seclusion_Status.DateTimeAdded ASC";
    $result=mysql_query($sql);
        // Start looping rows in mysql database.
        while($rows=mysql_fetch_array($result)){

查询返回 Seclusion_Status 记录,然后是 Period_rating 中的第一条记录,而不是其他记录。

 Array
[0] => 348
[ID] => 157
[1] => Y
[Arrived] => Y
[2] => N
[FTE] => N
[3] => 
[Rebuild] => 
[4] => 
[Text] => 
[5] => 2016-03-04 09:30:50
[DateTimeAdded] => 2016-03-04 09:30:50
[6] => Mr S Holland
[Staff] => Mr S Holland
[7] => K80222800
[Student_UPN] => K8022280
[8] => Refusing instructions
[Incident] => Refusing instructions
[9] =>  
[Period] =>  
[10] => 
[Period_In_ID] => 
[11] => Not sitting properly in class despite being asked
[Comment] => Not sitting properly in class despite being asked
[12] => K80222800
[UPN] => K80222800
[13] => Student Name
[Name] => Student Name
[14] => Year 9
[Year] => Year 9
[15] => Acer
[House] => Acer
[16] => 157
[17] => P2
[Slot_ID] => P2
[18] => 
[Rating] => 
[19] => 2016-03-04
[Date] => 2016-03-04
[20] => 348
[Seclusion_ID] => 348
[21] => 1
[Status] => 1

【问题讨论】:

    标签: mysql sql join


    【解决方案1】:

    查询返回 Seclusion_Status 记录,然后是 Period_rating 中的第一条记录,而不是其他记录。

    您有一个GROUP BY period_rating.Seclusion_ID,它指示 mysql 每个 Seclusion_ID 返回一条记录。去掉 group by 子句,查询会返回多条匹配的记录。

    【讨论】:

    • 好的。我已经删除了该声明,这样就解决了这个问题。它现在正在返回所有数据。我将这些数据写在表格的行中,并且每个学生都需要一个单独的行,但是对于该学生的所有 period_rating 记录都在同一行上。在它循环的那一刻,它正在为 Period_rating 中的每条记录在单独的行上写入同一个学生。
    • 我很抱歉,但这是一个与原始问题不同的问题。如果这个答案帮助你解决了你的问题,那么请接受这个答案并在他们自己的主题中提出任何后续问题!
    【解决方案2】:

    问题是如果你使用连接,如果数据在所有三个表中都存在,那么只有它会获取。

    如果你想获取表中的所有条目,你需要使用外连接,不幸的是你不能在mysql中使用外连接。

    但是你可以通过合并leftjoin结果和right join结果来获取结果

    【讨论】:

    • 左右连接外连接。 mysql 没有完全外连接,你正确地写道,它可以通过联合和左/右连接来模拟。
    猜你喜欢
    • 1970-01-01
    • 2021-09-09
    • 2011-07-20
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 2013-12-24
    • 2014-11-16
    • 1970-01-01
    相关资源
    最近更新 更多