MySQL JOIN Statement - Referenced Field in same Table

白昼怎懂夜的黑 提交于 2020-01-05 11:56:29

问题


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)


来源:https://stackoverflow.com/questions/18446545/mysql-join-statement-referenced-field-in-same-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!