仅选择唯一记录

时间:2014-04-26 07:05:58

标签: mysql

我正在尝试选择表中的所有记录,但隐藏重复的行。因此,如果2行完全相同(当然除了自动增量ID),则只应显示1行。

我认为这必须以不同的方式完成,但它仍然会给我重复的行。

SELECT DISTINCT *
FROM tbllulog
WHERE lulogluserial = $commandlu
ORDER BY `tbllulog`.`tbllulogid` DESC

我也试过这个:

SELECT DISTINCT lulogtimestamp,
                lulogmoveemployee,
                lulogsource,
                lulogaction,
                lulogluoutput0status,
                lulogluinput0status
FROM tbllulog
WHERE lulogluserial = $commandlu
ORDER BY `tbllulog`.`tbllulogid` DESC

但这也给了我重复

任何人都可以指出我缺少的东西吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

使用DISTINCT GROUP BY并将tbllulogid添加到SELECT

 SELECT DISTINCT tbllulogid,
        lulogtimestamp,
        lulogmoveemployee,
        lulogsource,
        lulogaction,
        lulogluoutput0status,
        lulogluinput0status
   FROM tbllulog 
        WHERE lulogluserial = $commandlu 
        GROUP BY `tbllulog`.`tbllulogid` 
        ORDER BY `tbllulog`.`tbllulogid` DESC

答案 1 :(得分:1)

试试这个

DECLARE @type varchar(50);
DECLARE @num int;
SET @type = '';
SET @num  = 1;

SELECT * FROM
(
SELECT lulogtimestamp,
       lulogmoveemployee,
       lulogsource,
       lulogaction,
       lulogluoutput0status,
       lulogluinput0status
       @num := if(@type = lulogmoveemployee, @num + 1, 1) as row_number,
       @type := lulogmoveemployee As Dummy
FROM tbllulog
WHERE lulogluserial = $commandlu
ORDER BY `tbllulog`.`tbllulogid` DESC
) T WHERE row_number = 1