2012-09-04 177 views
0

2代MySQL表數據我有2個表city_sessions_1city_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; 

注意這些表沒有任何主鍵,但他們有他們的索引定義。兩個表具有相同的行數。但預計一些數據會有所不同。

如何比較這兩個表格的數據?

+0

出來放你想 –

+0

http://whatHaveYouTried.com –

+0

什麼是你的[交集]後(http://en.wikipedia.org/wiki/Intersection_(set_theory))(什麼是相同的)或[對稱差異](http://en.wikipedia.org/wiki/Symmetric_difference)(有什麼不同)? – eggyal

回答

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 
+0

您可以將'UNION'更改爲'UNION ALL'以加快速度。無論如何+1是的,一個小調整,但一個調整。 – fancyPants

+0

@tombom'UNION'保證不會產生重複,前半部分city_sessions_1.city_id allways'not null',後半部分總是'null'。這可以立即在重複數據刪除過程中找到(city_sessions_1是第一個查詢的驅動表),從而導致接近零的開銷。 –

相關問題