我有以下查询正常工作。
SELECT d.customer_id,
d.fname,
d.lname,
m.lastDate,
(SELECT COUNT(order_id)
FROM `orders`
WHERE `customer_id`=d.customer_id
) AS 'total_orders',
d.isActive
FROM customers d
JOIN `orders` m ON m.order_id=
(SELECT order_id
FROM `orders`
WHERE customer_id=d.customer_id
ORDER BY order_id DESC LIMIT 1
)
WHERE d.user_id=382
AND d.customer_id NOT IN
(SELECT `customer_id`
FROM `orders`
WHERE `balance`>0
AND `isActive`=1
)
上面的查询工作正常但是当添加和联合查询还包括没有下任何订单的客户时,它确实有效。
SELECT d.customer_id,
d.fname,
d.lname,
m.lastDate,
(SELECT COUNT(order_id)
FROM `orders`
WHERE `customer_id`=d.customer_id
) AS 'total_orders',
d.isActive
FROM customers d
JOIN `orders` m ON m.order_id=
(SELECT order_id
FROM `orders`
WHERE customer_id=d.customer_id
ORDER BY order_id DESC LIMIT 1
)
WHERE d.user_id=382
AND d.customer_id NOT IN
(SELECT `customer_id`
FROM `orders`
WHERE `balance`>0
AND `isActive`=1
)
UNION
#customer WITH NO ORDERS
SELECT `customer_id`,`fname`,`lname`,`state`,`city`,`isActive`
FROM `customers`
WHERE `user_id`=382
AND `isActive` >-1
AND `customer_id` NOT IN
(SELECT `customer_id`
FROM `orders`
)
它在我的phpmyadmin中显示此错误
此类型的子句先前已被解析(接近选择)
答案 0 :(得分:0)
根据您的评论,我认为您不想使用union
- 您想要使用outer join
。以下是使用joins
而非所有correlated subqueries
的查询的略微简化版本。
SELECT d.customer_id, d.fname, d.lname, d.isactive,
o.lastdate,
Count(o2.order_id) AS 'total_orders'
FROM customers d
LEFT JOIN (SELECT MAX(order_id) order_id, customer_id
FROM orders
GROUP BY customer_id) m on d.customer_id = m.customer_id
LEFT JOIN orders o on m.order_id = o.order_id
LEFT JOIN orders o2 on d.customer_id = o2.customer_id
AND o2.balance > 0 AND o2.isactive = 1
WHERE d.user_id = 382
AND o2.customer_id IS NULL
GROUP BY d.customer_id
BTW - 在使用union
语句时,检查您的修改时,每个select
列表中的列数必须相同。第二个查询中的state
和city
字段可能与第一个查询中的lastDate
和count
字段的数据类型不同。