我有四个SQL Server数据库表:
inventory
inventory2
bdo
details
结构如下:
广告
AllocationID MSISDN
1 3018440225
2 3028431115
Inventory2
AllocationID MSISDN
1 3011234567
2 3026440657
3 3454159650
BDO
BDO_ID BDO_MSISDN
1 3457076952
2 3005000475
详情
AllocationID MSISDN
3 3454159650
现在我需要从以下查询中获取记录:
select a.msisdn, b.bdo_id
from details a, bdo b, inventory c, inventory2 d
where
a.msisdn = 3454159650
and (a.allocationid = c.allocationid) or (a.allocationid = d.allocationid)
and (c.bdo_id = b.bdo_id) or (d.bdo_id = b.bdo_id)
此查询返回多于1个结果(完全相同)为什么会这样?如果我错了,请纠正我的概念和查询。
答案 0 :(得分:2)
您的查询形式非常奇怪。首先,您应该使用join
语法。其次,您似乎希望在两个库存表之间建立联合:
select d.msisdn, b.bdo_id
from (select i.*
from (select i.* from inventory i union all
select i2.* from inventory i2
) i
) i join
details d
on d.allocationid = i.allocationid join
bdo b
on i.bdo_id=b.bdo_id
where d.msisdn = 3454159650;
将查询结构化为显式连接应该使其更有效,并且应该使其更容易理解,正确和维护。
编辑:
您可能缺少某些表中的某些记录。尝试将此版本与left outer join
:
select d.msisdn, b.bdo_id
from details d left outer join
(select i.*
from (select i.* from inventory i union all
select i2.* from inventory i2
) i
) i
details d
on d.allocationid = i.allocationid left outer join
bdo b
on i.bdo_id=b.bdo_id
where d.msisdn = 3454159650;
答案 1 :(得分:1)
我很惊讶它返回任何东西。你指的是一个不存在的bdo_id字段。
您的主要问题是and
优先于or
试试这个
select a.msisdn,b.bdo_id
from details a,bdo b,inventory c,inventory2 d
where
a.msisdn=3454159650
and ((a.allocationid = c.allocationid) or (a.allocationid = d.allocationid))
and ((c.bdo_id=b.bdo_id) or (d.bdo_id=b.bdo_id))
答案 2 :(得分:1)
您的查询未返回值。此查询引发错误。 查询的最后一行
and (c.bdo_id = b.bdo_id) or (d.bdo_id = b.bdo_id)
C是您的库存表,库存表没有列名与bdo_id
和
D是您的inventory2表,inventory2表没有列名与bdo_id