SQL查找对于一列具有相同值而在其他列中具有不同值的行

时间:2016-09-06 16:23:03

标签: mysql sql

我需要找到共享同一列的行,但在其他列中也有不同的值。我创建了一个SQL Fiddle以供参考。我的结果仍然是0.任何帮助将不胜感激。

CREATE TABLE IF NOT EXISTS `tracking` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `IP` varchar(255) NOT NULL,
  `MAC` varchar(255) NOT NULL,
  `UUID` varchar(255) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `isActive` tinyint(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

--
-- Dumping data for table `tracking`
--

INSERT INTO `tracking` (`id`, `IP`, `MAC`, `UUID`, `timestamp`, `isActive`) VALUES
(1, '98.186.154.212.12', '10:DD:B1', ' uuid:a5fadbbd ', '2016-09-06 15:03:52', 0),
(2, '423.2362.234', '2534623523523', ' uuid:a5fadbbd ', '2016-09-06 15:15:28', 0),
(3, '98.186.154.212.12', '10:DD:B1', ' uuid:a5fadbbd ', '2016-09-06 15:03:52', 0),
(4, '98.186.154.212.12', '10:DD:B1', ' uuid:a5fadbbd ', '2016-09-06 15:04:09', 0),
(5, '98.186.154.212.12', '10:DD:B1', ' uuid:a5fadbbd ', '2016-09-06 15:04:44', 0),
(6, '98.186.154.212.12', '10:DD:B1', ' uuid:a5fadbbd ', '2016-09-06 15:04:44', 0),
(7, '98.186.154.212.12', '10:DD:B1', ' uuid:a5fadbbd ', '2016-09-06 15:06:28', 0),
(8, '98.186.154.212.12', '10:DD:B1', ' uuid:a5fadbbd ', '2016-09-06 15:06:28', 0),
(9, '98.186.154.212.12', '10:DD:B1', ' uuid:a5fadbbd ', '2016-09-06 15:06:28', 0);


SELECT * 
    FROM tracking t 
    WHERE timestamp = 
         ( SELECT MAX(timestamp) 
           FROM tracking
           WHERE UUID = t.UUID 
              AND (IP <> t.IP OR MAC <> t.MAC)) 
    GROUP BY id;

http://sqlfiddle.com/#!9/c0ae3b6/4

期望的结果如下所示:

1 个答案:

答案 0 :(得分:0)

不清楚MAX(timestamp)与问题的关系。如果您只想查找在一列中匹配但在其他列中不同的行,则可以使用JOIN

SELECT *
FROM tracking AS t1
JOIN tracking AS t2 
ON t1.uuid = t2.uuid
 AND (t1.ip != t2.ip OR t1.mac != t2.mac)
 AND t1.id < t2.id

额外t1.id < t2.id条件可防止在t1t2交换时出现重复项。

DEMO