2014-12-04 46 views
0

我有一个像下面SQL服务器 - OR子句中加入混乱

Package 

PACK_ID | DESCR | BRAND_ID 
    1  | Shoes | 20 
    2  | Cloths| NULL 


ITEMS 

ITEM_ID | PACK_ID | BRAND_ID 
100  | 1  | 10 
101  | 1  | NULL 
102  | 1  | 10 

BRANDS 
NAME | BRAND_ID 
A | 10 
B | 20 

我想编写一个查询,列出多少个项目由同一品牌的分组包是否有表结构。如果品牌没有在物品中定义,它应该从包装中获得。 注:Brand_id两个包和项目可以为空

我的查询是这样的

SELECT count (*) as count,p.descr as descr,b.name FROM [items] item 
inner join [package] p on item.pack_id= p.pack_id 
inner join [brands] b on b.brand_id = item.brand_id or b.brand_id = p.brand_id 
where p.pack_id = 1 
group by b.name,p.descr 

,我的结果是

COUNT | descr | NAME 
2  | Shoes | a 
3  | Shoes | B 

,而我希望得到的结果是这样的

COUNT | descr | NAME 
2  | Shoes | a 
1  | Shoes | B 

请问你能提出我的代码有什么问题吗?提前致谢。

回答

1

尝试使用您的加盟条件ISNULL:

SELECT count (*) as count,p.pack_id as pack_id,b.name FROM [items] item 
inner join [package] p on item.pack_id= p.pack_id 
inner join [brands] b on b.brand_id = ISNULL(item.brand_id, p.brand_id) 
where p.pack_id = 1 
group by b.name,p.pack_id 

你OR是导致它加入到多行,这应该是默认使用的项目,然后回落到包。

1

我倾向于通过获得品牌这个包来实现这个目标。然后决定在select使用哪一个:这种方法

SELECT count(*) as count, p.descr as descr, coalesce(bi.name, bp.name) as name 
FROM [items] item inner join 
    [package] p 
    on item.pack_id= p.pack_id left join 
    [brands] bi 
    on bi.brand_id = item.brand_id left join 
    brands bp 
    on b.brand_id = p.brand_id 
where p.pack_id = 1 
group by coalesce(bi.name, bp.name), p.descr; 

一个关键优势是性能。当连接表达式或or条件时,数据库往往做得不好。