比较具有相同结构的2个Mysql表的数据

时间:2012-09-04 12:07:18

标签: mysql data-comparison

我有2个表 city_sessions_1 city_sessions_2 两个表的结构相似

CREATE TABLE `city_sessions_1` (
  `city_id` int(11),
  `session_date` date,
  `start_time` varchar(12),
  `end_time` varchar(12) ,
  `attendance` int(11) ,  
  KEY `city` (`city_id`),
  KEY `session_date` (`session_date`)
) ENGINE=MyISAM;

请注意,这些表没有任何主键,但它们的索引已定义。两个表都有相同的行数。但预计一些数据会有所不同。

如何比较这两个表的数据?

1 个答案:

答案 0 :(得分:1)

-- We start with the rows in city_session_1, and their fit in city_session_2
SELECT
  * -- or whatever fields you are interested in
FROM city_sessions_1 
  LEFT JOIN city_sessions_2 ON city_sessions_1.city_id=city_sessions_2.city_id
WHERE 
  -- Chose only those differences you are intersted in
  city_sessions_1.session_date<>city_session_2.session_date
  OR city_sessions_1.start_time<>city_session_2.start_time
  OR city_sessions_1.end_time<>city_session_2.end_time
  OR city_sessions_1.attendance<>city_session_2.attendance

UNION 

-- We need those rows in city_session_2, that have no fit in city_session_1
SELECT
  * -- or whatever fields you are interested in
FROM city_sessions_2 
  LEFT JOIN city_sessions_1 ON city_sessions_1.city_id=city_sessions_2.city_id
WHERE city_sessions_1.city_id IS NULL