2013-03-02 63 views
0

我有兩個表。一個具有所有選項,一個具有用戶選擇的選項以及一些它們可能不在選項表中的選項。聯合兩個查詢和標記重複

我需要工會的數據,所以我得到一個結果集,它包含了所有的選項,以及用戶的選項,不知何故標誌,它是唯一的用戶,並與主數據選項重疊...

例...

選項

`COLOR` | `ANIMAL` 
--------------------- 
RED  | DOG 
BLUE  | DOG 
GREEN  | DOG 
YELLOW | CAT 
PINK  | CAT 
ORANGE | CAT 

用戶選擇的選項

`COLOR` | `ANIMAL` 
------------------ 
GREEN | SNAKE 
BLUE | DOG 
PINK | CAT 
PURPLE | CAT 

我的結果需要看起來像...

`COLOR` | `ANIMAL`| `DUPLICATE_OR_NEW` 
---------------------------------------- 
RED  | DOG  | 0 
BLUE | DOG  | 1 
GREEN | DOG  | 0 
YELLOW | CAT  | 0 
PINK | CAT  | 1 
ORANGE | CAT  | 0 
PURPLE | CAT  | 1 
GREEN | SNAKE | 1 

的排序順序並不在這種情況下無所謂。我正在嘗試使用UNION,但我認爲我需要通過將兩個表連接在一起來完成。到目前爲止我還沒有提出解決方案。

+0

但什麼是查詢? – 2013-03-02 00:06:29

回答

0

這可以被稱爲作弊,但它會工作

SELECT COLOR, ANIMAL, sum(DUPLICATE_OR_NEW) 
FROM 
(
SELECT COLOR, ANIMAL, 1 as DUPLICATE_OR_NEW FROM options 
UNION ALL 
SELECT COLOR, ANIMAL, 2 as DUPLICATE_OR_NEW FROM UserSelection 
) as UTable 
GROUP BY COLOR, ANIMAL 

-- 1 = unchosen option 
-- 2 = new user added option 
-- 3 = option exsisted chosen by user 

看到SQL小提琴http://sqlfiddle.com/#!2/01c79/2

+0

我喜歡作弊的作弊。你的答案約有95%。由於減1,我的表2中不存在於表1中的項目顯示零。簡單的解決方法是將SELECT COLOUR,ANIMAL,'1'更改爲DUPLICATE_OR_NEW FROM table_name2 ****,將SELECT COLOUR,ANIMAL,'2'更改爲DUPLICATE_OR_NEW FROM table_name2。這會在重疊項目的列中放置2,併爲新項目留下1。這對我的使用很好,因爲我可以說大於零的地方。謝謝!!! – user2125504 2013-03-02 00:19:32

0

另一種方式來處理這個:

select color, animal, 1 as duplicate_or_new 
from UserSelected 
union all 
select color, animal, 0 as duplicate_or_new 
from options o 
where not exists (select 1 from UserSelected us where us.color = o.color and us.animal = o.animal) 

的正確方法與union all做/ group by:

select color, animal, max(which) as duplicate_or_new 
from (select color, animal, 1 as which 
     from UserSelected 
     union all 
     select color, animal, 0 as which 
     from options 
    ) t 
group by color, animal 

下面的查詢創建兩個獨立的標誌:

select color, animal, max(isUser) as IsUser, max(isOption) as IsOption 
from (select color, animal, 1 as IsUser, 0 as IsOption 
     from UserSelected 
     union all 
     select color, animal, 0 as IsUser, 1 as IsOption 
     from options 
    ) t 
group by color, animal 

你可以把它們放在一個case語句格式的信息:

(case when max(isUser) = 1 and max(isOption) = 1 then 'both' 
     when max(isUser) = 1 then 'user' 
     when max(isOption) = 1 then 'option' 
     else 'impossible' 
end) 
+0

如何判斷選項是完全「新」還是從現有列表中選擇? – Mortalus 2013-03-02 00:40:27