2013-02-21 100 views
0

我有兩個表:連接來自所有表的值;

CREATE TABLE `events` (
    `id` double NOT NULL,`value` int, PRIMARY KEY (`id`)); 

CREATE TABLE `updates` (
    `id` double NOT NULL AUTO_INCREMENT, 
    `action` enum('delete','update') DEFAULT NULL, 
    `event_id` double DEFAULT NULL, 
    PRIMARY KEY (`id`)); 

,並試圖使查詢這將讓所有的值從events,並從更新得值,即使event_id在更新不會在事件表中存在(只有當動作是「刪除「)

使用

SELECT ifnull(e.id,u.event_id) AS event_id, 
     e.value,ifnull(u.action,'update') AS ACTION, 
     ifnull(u.id,-1) as update_id 
     FROM events e 
     LEFT JOIN updates u ON e.id=u.event_id 

我越來越

|  EVENT_ID | VALUE | ACTION | UPDATE_ID | 
---------------------------------------------- 
| 1361264148710 |  1 | update |  -1 | 
| 1361264148711 |  2 | update |  -1 | 
| 1361264148712 |  5 | update |  -1 | 
| 1361264148713 | 10 | update |   1 | 
| 1361264148714 | 11 | update |   2 | 
| 1361264148714 | 11 | update |   3 | 
| 1361264148714 | 11 | update |   4 | 
| 1361264148715 | 14 | update |   5 | 
| 1361264148716 |  1 | update |   6 | 
| 1361264148717 | 17 | update |   8 | 
| 1361264148718 | 22 | update |  10 | 
| 1361264148719 | 23 | update |  11 | 

我的目標是獲得:

|  EVENT_ID | VALUE | ACTION | UPDATE_ID | 
----------------------------------------------- 
| 1361264148710 |  1 | update |  -1 | 
| 1361264148711 |  2 | update |  -1 | 
| 1361264148712 |  5 | update |  -1 | 
| 1361264148713 |  10 | update |   1 | 
| 1361264148714 |  11 | update |   2 | 
| 1361264148714 |  11 | update |   3 | 
| 1361264148714 |  11 | update |   4 | 
| 1361264148715 |  14 | update |   5 | 
| 1361264148716 |  1 | update |   6 | 
| 1361264148708 | (null) | delete |   7 | 
| 1361264148717 |  17 | update |   8 | 
| 1361264148709 | (null) | delete |   9 | 
| 1361264148718 |  22 | update |  10 | 
| 1361264148719 |  23 | update |  11 | 

here is sqlfiddle

回答

0

看起來要UNION結果:

SELECT ifnull(e.id,u.event_id) AS event_id, 
     e.value,ifnull(u.action,'update') AS ACTION, 
     ifnull(u.id,-1) as update_id 
     FROM events e 
     LEFT JOIN updates u ON e.id=u.event_id 
UNION 
SELECT u.event_id AS event_id, 
     e.value,ifnull(u.action,'update') AS ACTION, 
     ifnull(u.id,-1) as update_id 
     FROM updates u 
     LEFT JOIN events e ON e.id=u.event_id 
    WHERE e.id IS NULL 

而更新後的提琴:http://sqlfiddle.com/#!2/b1eb7/7

由於@njk在評論中指出,這可以簡化爲:

SELECT ifnull(e.id,u.event_id) AS event_id, 
     e.value,ifnull(u.action,'update') AS ACTION, 
     ifnull(u.id,-1) as update_id 
FROM 
    (SELECT id AS id FROM events 
    UNION 
    SELECT event_id AS id FROM updates) a 
LEFT JOIN events e ON e.id = a.id 
LEFT JOIN updates u ON u.event_id = a.id 
ORDER BY update_id 

這裏是updated Fiddle與兩個 - 我認爲首先進行更好看的執行計劃。

+0

但我需要'WHERE u.id> N'它可能與工會? – 2013-02-21 02:56:19

+0

是的,可以將WHERE標準添加到您的UNION中 - 將它添加到兩個 - 您是否看到更新的小提琴 - 看起來像您期望的結果。 – sgeddes 2013-02-21 02:57:59

+0

hm,對我來說,看起來很奇怪,我必須複製此類請求的代碼, – 2013-02-21 02:58:57

相關問題