我长期陷入困境。
我有一个orders
客户的表格,我希望得到4种类型的结果,如
1st: All orders with status=place
然后2nd: All orders with status=place and customer is new
(此客户的订单表中没有以前的记录),
然后3rd: All orders with status=place and customer have at least 1 order delivered and never returned previous order
,
然后4th: All orders with status=place and customer have atleast 1 order with status=returned
第一步的查询工作正常,但我不知道得到其他结果。我知道它就像一个任务,但我需要帮助。
我尝试第一步
SELECT o.order_id, o.customer_id, o.order_status_id,
FROM `order` o
WHERE (o.order_status_id = '1'
AND o.payment_code <> 'paytabs'
AND o.payment_code <> 'pp_express')
ORDER BY o.order_id DESC
这给了我第一步的完美结果。我正在使用OpenCart 2.2.0.0
数据库结构
|order_id |status | payment_code |customer_id |
|---------|-------|--------------|------------|
| 10 | place | cod | 5 |
| 11 | delvr | cod | 4 |
| 12 | return| pp_express | 5 |
| 13 |process| paytabs | 2 |
任何帮助或建议将不胜感激。 向我询问你需要的任何东西。
答案 0 :(得分:1)
不确定您的数据库结构,但我会尝试...
广告2:
SELECT o.order_id, o.customer_id, o.order_status_id,
FROM `order` o
WHERE (o.order_status_id = '1'
AND o.payment_code <> 'paytabs'
AND o.payment_code <> 'pp_express')
AND o.customer_id NOT IN (SELECT o2.customer_id from order o2 WHERE o2.order_id != o.order_id AND o2.customer_id = o.customer_id)
ORDER BY o.order_id DESC
因此,广告4:
SELECT o.order_id, o.customer_id, o.order_status_id,
FROM `order` o
WHERE (o.order_status_id = '1'
AND o.payment_code <> 'paytabs'
AND o.payment_code <> 'pp_express')
AND o.customer_id IN (SELECT o2.customer_id from order o2 WHERE o2.order_status = 'returned')
ORDER BY o.order_id DESC
现在为3:
SELECT o.order_id, o.customer_id, o.order_status_id,
FROM `order` o
WHERE (o.order_status_id = '...?')
AND o.customer_id NOT IN (SELECT o2.customer_id from order o2 WHERE o2.order_status = 'returned')
AND o.customer_id IN (SELECT o3.customer_id from order o3 WHERE o3.order_status = 'delivered')
ORDER BY o.order_id DESC
BTW:我强烈建议重命名表“order”,因为“order”是一个SQL关键字。
答案 1 :(得分:0)
我认为如果你想用一个查询来做这件事,你应该使用Union。
其他方式,当同一客户遇到2个contidions时,你只会看到一个。
答案 2 :(得分:0)
对于第二个查询:您只需在SQL中添加一个AND子句: AND user_id = 0
假设插入新订单时user_id = 0(如果这是新用户)
答案 3 :(得分:0)
查询: 查询是根据您提出的问题和您的订单表结构(我正在考虑您没有创建任何列,如created_at和updated_at)。
从订单中选择*,其中status =&#39; place&#39;;
从订单中选择orders.order_id,orders.customer_id,其中status =&#39; place&#39; GROUP BY order_id,customer_id HAVING COUNT(customer_id)= 1;
从订单a astatus中选择a.order_id,a.customer_id(从订单b中选择b.status,其中a.order_id = b.order_id和状态&lt;&gt;&#39;返回&# 39;)和a.status =&#39;地点&#39; GROUP BY a.order_id,a.customer_id HAVING COUNT(a.customer_id)&gt; = 1;
从订单a astatus中选择a.order_id,a.customer_id(从订单b中选择b.status,其中a.order_id = b.order_id和status =&#39; return&#39;)和a.status =&#39;地点&#39; GROUP BY a.order_id,a.customer_id HAVING COUNT(a.customer_id)&gt; = 1