【问题标题】:MySQL JOIN Statement - Referenced Field in same TableMySQL JOIN 语句 - 同一个表中的引用字段
【发布时间】:2013-08-26 14:28:28
【问题描述】:

如何获取表中除(已被引用的订单和类型为-1的订单)以外的所有订单的列表

订单表:

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

类似:

list = ArrayList();

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

如何在 MySQL 语句中做到这一点?

这个语句的结果也一样,但是使用了 JOIN....等:

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

谢谢

【问题讨论】:

  • 你用什么语言访问mysql?爪哇?你试过什么吗?
  • 语言不重要,我只需要 SQL 语句(仅查询)
  • 为什么订单表似乎引用了自己?
  • re: 也与此语句的结果相同,但使用了 JOIN....等。您还想加入哪张桌子?您在问题中只告诉了我们一张桌子。

标签: mysql join field


【解决方案1】:

这将为您提供那些被引用和有效的记录

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

【讨论】:

【解决方案2】:

你在找这个吗:

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

【讨论】:

  • 是的,但是是否可以使用 JOIN ...等重写它?避免选择 2x
  • 两次选择没有问题。 MySql 将生成一个运行查询的快速计划。
  • 正确的SELECT语句在问题中,如何使用JOIN重写它?
  • 我不明白。这 IS 是带有 WHERE 子句的单个 select 语句。
  • 请参阅 skv 答案。无论如何,谢谢你的回答/cmets
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
相关资源
最近更新 更多