MySQL加密查询,限制一次加入

时间:2017-09-26 15:23:15

标签: mysql sql join

我正在进行 MYSQL 查询,从多个联接中提取数据。

select students.studentID, students.firstName, students.lastName, userAccounts.userID, userstudentrelationship.userID, userstudentrelationship.studentID, userAccounts.getTexts, reports.pupID, contacts.pfirstName, contacts.plastName, reports.timestamp

 from userstudentrelationship  

join userAccounts on (userstudentrelationship.userID = userAccounts.userID)
join students on (userstudentrelationship.studentID = students.studentID) 
join reports on (students.studentID = reports.studentID) 
join contacts on (reports.pupID = contacts.pupID) 

where userstudentrelationship.studentID = "10000005" AND userAccounts.getTexts = 1 ORDER BY reports.timestamp DESC LIMIT 1

我有一个独特的情况,我希望其中一个连接(报告连接)仅限于该表的最新结果(由reports.timestamp desc limit 1的命令是我使用的),而不是限制整个查询的结果数量。

通过运行上面的查询,我得到了我期望的数据,但只有一条记录应该返回几个。

我的问题:

如何修改此查询以确保我收到所有可用的可用记录,同时确保仅使用报告加入的最新记录?我希望每条记录可能包含与其他联接不同的数据,但此查询返回的所有记录将共享相同的报告记录

2 个答案:

答案 0 :(得分:3)

如果我理解这个问题;可以为一组数据(下面的别名Z)添加一个连接,该数据具有每个学生的最大时间戳;从而限制每个学生的一份报告记录(最近)。

SELECT students.studentID
     , students.firstName
     , students.lastName
     , userAccounts.userID
     , userstudentrelationship.userID
     , userstudentrelationship.studentID
     , userAccounts.getTexts
     , reports.pupID
     , contacts.pfirstName
     , contacts.plastName
     , reports.timestamp
FROM userstudentrelationship  
join userAccounts 
  on userstudentrelationship.userID = userAccounts.userID
join students 
  on userstudentrelationship.studentID = students.studentID
join reports 
  on students.studentID = reports.studentID
join contacts 
  on reports.pupID = contacts.pupID
join (SELECT max(timestamp) mts, studentID 
      FROM REPORTS 
      GROUP BY StudentID) Z
  on reports.studentID = Z.studentID
 and reports.timestamp = Z.mts
WHERE userstudentrelationship.studentID = "10000005" 
  AND userAccounts.getTexts = 1 
ORDER BY reports.timestamp 

答案 1 :(得分:1)

获取所有记录,你应该避免在查询结束时限制1 要从报告表中连接一行,您可以使用子查询作为

select 
    students.studentID
    , students.firstName
    , students.lastName
    , userAccounts.userID
    , userstudentrelationship.userID
    , userstudentrelationship.studentID
    , userAccounts.getTexts
    , t.pupID
    , contacts.pfirstName
    , contacts.plastName
    , t.timestamp

from userstudentrelationship  

join userAccounts on userstudentrelationship.userID = userAccounts.userID
join students on userstudentrelationship.studentID = students.studentID
join (
  select * from reports
  order by reports.timestamp  limit 1
) t on students.studentID = t.studentID
join contacts on reports.pupID = contacts.pupID 

where userstudentrelationship.studentID = "10000005" 
AND userAccounts.getTexts = 1