订单表:
Order_items表:
用户表:
$sql[2] = "SELECT u.name, COUNT(o.user_id) AS order_count, (oi.quantity * p.price) AS total_price FROM users AS u
INNER JOIN orders AS o ON u.id = o.user_id
INNER JOIN order_items AS oi ON oi.order_id = o.id
INNER JOIN products AS p ON p.id = oi.product_id
GROUP BY u.name
ORDER BY ertek DESC";
我想要计算每个用户的订单数量。示例:像托马斯有3个订单,但我的代码是写1,我想写托马斯(3)。花了多少钱,但这个工作正常。知道怎么解决吗?
答案 0 :(得分:0)
对于您要求的内容,查询应如下所示:
SELECT u.name,
COUNT(DISTINCT o.id) as order_count,
-------------^
SUM(oi.quantity * p.price) as total_price
-------^
FROM users u INNER JOIN
orders o
ON u.id = o.user_id INNER JOIN
order_items oi
ON oi.order_id = o.id INNER JOIN
products p
ON p.id = oi.product_id
GROUP BY u.name
ORDER BY order_count DESC; -- I assume `ertek` is just a translation issue
我突出了重要的变化。
答案 1 :(得分:0)
您可以尝试以下查询。
select u.name, (select count(*) from orders o where o.user_id=u.id) as
order_count, (select sum(oi.quantity * p.price) from orders AS o INNER
JOIN order_items AS oi ON oi.order_id = o.id INNER JOIN products AS p ON
p.id = oi.product_id where o.user_id=u.id) as total_price from users u
可能会对你有帮助。