MySQL JOIN Statement - Referenced Field in same Ta

2019-08-01 00:56发布

问题:

how to get a list of all orders in the table except (orders which has been referenced and type of -1)

orders Table:

id   |   reference_id  | type
---------------------------------- 
1    |                 | 1
---------------------------------- 
2    |                 | 1
---------------------------------- 
3    |   1             | -1
----------------------------------

something like:

list = ArrayList();

if( order.type > 0 ){
    if( order.id != other_order.reference_id )
        list.add(order)
}

how to do this in MySQL Statement?

also the same result of this statement but using JOIN....etc:

select * from orders as a
where a.type > 0 AND not exists 
(select * from orders as b where a.id = b.ref_id)

Thanks

回答1:

This will give you those records which are referenced and those which are valid

SELECT * 
FROM   yourtable A 
       INNER JOIN yourtable B 
               ON A.reference_id = B.order_id 
WHERE  B.reference_type > 0; 


回答2:

Are you looking for this:

select * from orders
where not exists 
(select * from orders o where o.id = o.reference_id and type = -1)


标签: mysql join field