2016-12-19 46 views
0

Orders表:PHP/MySQL的計數訂單

enter image description here

ORDER_ITEMS表:

enter image description here

用戶表:

Users

$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)。花了多少錢,但這個工作正常。任何想法如何解決它?

回答

2

您可以嘗試下面的查詢。

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 

可能這會幫助你。

+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

dosnt work。它只有7(埃裏克3 - 格雷西亞2 - 亞歷克斯1 - 托馬斯1),但我有更多的訂單比7,任何其他想法如何解決它? –