将左连接限制为View中的最新日期

时间:2014-08-27 23:53:47

标签: php sql join

我的查询已连接到一个表格,我只希望根据dtm查看最后输入的结果

这是我的查询

CREATE OR REPLACE VIEW vwc_students AS 
SELECT u_students.stud_id,u_students.stud_firstname, u_students.stud_middlename,u_students.stud_lastname, CONCAT_WS(' ',u_userse.user_firstname,u_userse.user_lastname) AS stud_editeduser, u_students.stud_edited, u_tbleeditlog.editedDtm
FROM u_students
JOIN u_studsites ON u_studsites.uss_studid = u_students.stud_id
JOIN u_locations ON u_locations.loc_id = u_students.stud_base
JOIN u_users ON u_users.user_id = u_students.stud_loggedid
LEFT JOIN (SELECT editedID, editedDtm FROM u_tbleeditlog WHERE editSite = 1 AND editType = 1 ORDER BY editedDtm DESC LIMIT 1) u_tbleeditlog ON u_tbleeditlog.editedID = u_students.stud_id
LEFT JOIN u_users AS u_userse ON u_userse.user_id = u_tbleeditlog.editedID
WHERE u_studsites.uss_siteid = '1'

但我收到错误#1349 - View's SELECT contains a subquery in the FROM clause

我从Limiting a left join to returning one result?MySQL JOIN Multiple Tables With LIMIT Last Table By DateTime per result

获得了代码示例

任何人都可以告诉我,我尝试做的事情是否有可能,如果有的话,怎么样? :)

更新

好的,我现在有以下2个建议的观点

CREATE OR REPLACE VIEW vwc_students AS 
SELECT u_students.stud_id,u_students.stud_firstname, u_students.stud_middlename,u_students.stud_lastname, u_userse.editedEditor AS stud_editeduser, u_userse.editedDtm AS stud_edited
FROM u_students
JOIN u_studsites ON u_studsites.uss_studid = u_students.stud_id
JOIN u_locations ON u_locations.loc_id = u_students.stud_base
JOIN u_users ON u_users.user_id = u_students.stud_loggedid
LEFT JOIN vwu_editlog AS u_userse ON u_userse.editTypeID = u_students.stud_id AND u_userse.editType = 1
WHERE u_studsites.uss_siteid = '1'

CREATE OR REPLACE VIEW vwu_editlog AS 
SELECT u_tbleeditlog.*, CONCAT_WS(' ',u_users.user_firstname,u_users.user_lastname) AS editedEditor
FROM u_tbleeditlog
JOIN u_users ON u_users.user_id = u_tbleeditlog.editedID
ORDER BY u_tbleeditlog.editedDtm DESC LIMIT 1

但是这最后一个观点是将整个事情限制为1个结果!如何将每个唯一ID限制为1?我也收到了消息Current selection does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available.,即使在原始表格中它也在那里

2 个答案:

答案 0 :(得分:1)

重复: View's SELECT contains a subquery in the FROM clause

根据文件:

MySQL Docs

  • SELECT语句不能在FROM子句中包含子查询。

您的解决方法是为每个子查询创建一个视图。

然后从您的视图view_credit_status

中访问这些视图

所以也许你先做这样的事情:

CREATE OR REPLACE VIEW u_tbleeditlog AS 
 SELECT editedID, editedDtm
  FROM u_tbleeditlog
  WHERE editSite = 1
  AND editType = 1
  ORDER BY editedDtm DESC
  LIMIT 1;

答案 1 :(得分:1)

您错过了MySQL中的视图不允许from子句中的子查询这一事实。但是,它们被允许在select和where和having子句中。

文档:http://dev.mysql.com/doc/refman/5.0/en/create-view.html非常明确:

子视图不能在视图的FROM子句中使用。

在您的情况下,您可以将from子句重写为select子句中的相关子查询。您还可以使用多个视图层来执行所需的操作。

为每个FROM子句创建一个单独的视图。