简体   繁体   中英

Query for a match or return a null join

I have two tables one is the orders table with customer,items ordered 2nd table is the item info showing tag along items. Im making sure that the tag along item and the item its tagged along to are on both on the account, they do not need to be on the same order number 11 12. BC-customer MC-order number oitem-item on customer account

http://www.sqlfiddle.com/#!2/c6906c/4

CREATE TABLE orders
    (`bc` int, `mc` int,`OITEM` varchar(3))
;

INSERT INTO orders
    (`BC`, `MC`,`OITEM`)
VALUES
    (1, 11, 'HPB'),
    (1, 11, 'HPU'),
    (1, 11, 'TCU'),
    (1, 11, 'CPB'),
    (1, 11, 'HPU'),
    (1, 12, 'CPS'),
    (2, 11, 'CPA'),
    (2, 12, 'CPS'),
    (2, 12, 'TCU')
;

CREATE TABLE item_desc
    (`item` varchar(3), `tag` varchar(3))
;

INSERT INTO item_desc
    (`item`, `tag`)
VALUES
    ('FSU', 'CPS'),
    ('HPU', 'CPB'),
    ('FSU', 'CPB'),
    ('TCU', 'CPA')
;

I need to return a match or else show the null value: Here is the query I have written problem is I am showing both a match and a null value because CPS can be tag along to HPU or FSU.

select a.bc, a.mc, a.oitem as CP, b.tag, b.item, c.oitem as CP_Item
from orders a
left join item_desc b
on a.oitem = b.tag

left join orders c
on b.item = c.oitem

where a.oitem like 'CP%'
group by a.bc,a.mc,a.oitem,b.tag,b.item,c.oitem;

Currently Results Show:

BC  MC  CP  TAG ITEM    CP_ITEM
1   11  CPB CPB FSU     (null)
1   11  CPB CPB HPU     HPU
1   12  CPS CPS FSU     (null)
2   11  CPA CPA TCU     TCU
2   12  CPS CPS FSU     (null)

I want end result to show me the match and if no match than null but not both null and match because one match makes the account valid:

BC  MC  CP  TAG ITEM    CP_ITEM
1   11  CPB CPB HPU     HPU
1   12  CPS CPS FSU     (null)
2   11  CPA CPA TCU     TCU
2   12  CPS CPS FSU     (null)

You're almost there. Simply remove the b.item, c.oitem from your GROUP BY and you're all set.

select a.bc, a.mc, a.oitem as CP, b.tag, b.item, c.oitem as CP_Item
from orders a
left join item_desc b
on a.oitem = b.tag

left join orders c
on b.item = c.oitem

where a.oitem like 'CP%'
group by a.bc,a.mc,a.oitem,b.tag

http://www.sqlfiddle.com/#!2/c6906c/8

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM