【发布时间】:2017-09-12 23:30:20
【问题描述】:
我有两张桌子:
+-----------------------+
| Tables_in_my_database |
+-----------------------+
| orders |
| orderTaken |
+-----------------------+
订单中有属性
orderId, orderName, isClosed and orderCreationTime.
在orderTaken中,有属性
userId, orderId and orderStatus.
我们说什么时候
orderStatus = 1 --> the customer has taken the order
orderStatus = 2 --> the order has been shipped
orderStatus = 3 --> the order is completed
orderStatus = 4 --> the order is canceled
orderStatus = 5 --> the order has an exception
基本上我的项目的机制是这样运行的:具有唯一 userId 的用户将能够从网页上接受订单,其中每个订单也有自己唯一的 orderId。取完后,orderTaken 表会记录 userId、orderId 并初始设置 orderStatus = 1。然后店铺根据各种情况更新 orderStatus。一旦商店更新了 isClosed = 1,那么无论用户是否接受了这个订单,都不会显示(没有意义,但它只是查询中的 isClosed == 0)。
现在,我想构建一个网页,显示用户尚未接受的新订单(应该是他们的 orderIds 未记录在该用户的 userId 下的 orderTaken 表中的订单),以及用户已经使用 orderStatus 显示的订单但 orderStatus 不是 4 或 5,按 orderCreationTime DESC 分组(是的,如果我没有 orderTakenTime 但让我们保持这种方式可能没有意义),例如:
OrderId 4
Order Name: PetPikachu
orderStatus = 1
CreationTime: 5am
OrderId 3
Order Name: A truck of hamsters
orderStatus = 3
CreationTime: 4am
OrderId 2
New order
Order Name: Macbuk bull
CreationTime: 3am
OrderId 1
Order Name: Jay Chou's Album
orderStatus = 2
CreationTime: 2am
我根据所学知识编写了这个查询:
SELECT * FROM orders A WHERE A.isClosed == '0' FULL OUTER JOIN orderTaken B WHERE B.userId = '4' AND (B.orderStatus<>'4' OR B.orderStatus<>'5') ORDER BY A.orderCreationTime DESC;
显然这个查询不起作用,但我害怕有一个
ON A.orderId = B.orderId
从那时起,返回的表将消除 orderId 未记录在 orderTaken B 中的新订单。我还尝试了 NOT IN 子句,如
SELECT * FROM orders A WHERE A.isClosed = '0' AND A.orderId NOT IN (SELECT orderId FROM orderTaken B WHERE B.userId = '$userId' AND (B.orderStatus='4' OR B.orderStatus='5')) ORDER BY creationTime DESC;
此查询有效,但返回的表中没有 orderTaken B 的字段 orderStatus。我正在考虑在此查询之后添加另一个 JOIN orderTaken B 子句以从 B 获取字段,但我认为这不是编写查询的好方法。
我只是想将“NOT IN”和“FULL JOIN”结合起来。有人可以帮帮我吗?谢谢!
【问题讨论】:
标签: mysql join where notin full-outer-join