2013-03-02 48 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