I have four SQL Server database tables:
inventory
inventory2
bdo
details
Structure is as:
inventory
AllocationID MSISDN
1 3018440225
2 3028431115
Inventory2
AllocationID MSISDN
1 3011234567
2 3026440657
3 3454159650
BDO
BDO_ID BDO_MSISDN
1 3457076952
2 3005000475
Details
AllocationID MSISDN
3 3454159650
Now I need to get the records from following query:
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)
This query returns more than 1 result (all exactly same) why is it so??? if I am wrong please correct my concepts and query.
You have a very strange form for the query. First, you should use join
syntax. Second, you seem to want a union between the two inventory tables:
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;
Structuring the query as explicit joins should make it more efficient and should make it easier to understand, get correct, and maintain.
EDIT:
It is possible that you are missing some records in some tables. Try using this version with a 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;
I'm surprised it returns anything. You're referring to a bdo_id field that doesn't exist.
Your main problem is the priority of and
over or
Try this instead
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))
Your query does not return value. This query raise error. Last row of your query this
and (c.bdo_id = b.bdo_id) or (d.bdo_id = b.bdo_id)
C is your inventory table and inventory table has no column name with bdo_id
and
D is your inventory2 table and inventory2 table has no column name with bdo_id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.