在SQL视图中使用ORDER BY和LIMIT

时间:2014-08-28 02:48:20

标签: sql view limit

我正在尝试创建一个仅限于每个id的最后一个条目的视图

我的表格结构如下

CREATE TABLE IF NOT EXISTS `u_tbleeditlog` (
    `editID` bigint(20) NOT NULL AUTO_INCREMENT,
    `editType` int(1) NOT NULL,
    `editTypeID` bigint(20) NOT NULL,
    `editedID` bigint(20) NOT NULL,
    `editedDtm` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
    PRIMARY KEY (`editID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

我正在尝试创建一个只显示分配给TypeTypeID

的最后一个条目的视图

我的观点到目前为止

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个结果,我收到消息Current selection does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available.

所以说有1, 1, 2017-08-161, 1, 2016-05-14等多个值只会返回1, 1, 2017-08-16

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

2 个答案:

答案 0 :(得分:2)

使用not exists方法执行此操作以获取系列中的最后一行:

CREATE OR REPLACE VIEW vwu_editlog AS 
    SELECT el.*, CONCAT_WS(' ', u.user_firstname, u.user_lastname) AS editedEditor
    FROM u_tbleeditlog el JOIN
         u_users u
         ON u.user_id = el.editedID
    WHERE not exists (select 1
                      from u_tbleeditlog el2
                      where el2.editType = el.editType and
                            el2.editTypeID = el.editTypeID and
                            el2.editedDtm > el.editedDtm
                     );

答案 1 :(得分:0)

你必须使用GROUP BY和HAVING()。你用的是什么数据库?

看起来应该是这样的:

SELECT editType, editedDtm
FROM u_tbleeditlog AS u
GROUP BY editType, editedDtm
HAVING editedDtm = (SELECT MAX(editedDtm) FROM u_tbleeditlog WHERE editType = u.editType)
ORDER BY editedDtm DESC