1

我有四个 SQL Server 数据库表:

  1. inventory
  2. inventory2
  3. bdo
  4. details

结构如下:

存货

AllocationID   MSISDN
1              3018440225
2              3028431115

库存2

    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 个结果(全部完全相同)为什么会这样???如果我错了,请更正我的概念和查询。

4

3 回答 3

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;
于 2013-08-24T11:23:17.013 回答
1

我很惊讶它会返回任何东西。您指的是不存在的 bdo_id 字段。

你的主要问题是优先andor

试试这个

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))
于 2013-08-24T11:08:21.893 回答
1

您的查询不返回值。此查询引发错误。您查询的最后一行

and (c.bdo_id = b.bdo_id) or (d.bdo_id = b.bdo_id)

C 是您的库存表,库存表没有带有 bdo_id 的列名

D 是您的 inventory2 表,inventory2 表没有带有 bdo_id 的列名

于 2013-08-24T14:18:45.920 回答