SQL Count有3个表

时间:2018-06-06 19:47:34

标签: mysql sql count

我需要帮助一个sql选择混合3个表的内容,表格是:

Clients
client_id   | name    | lastname
1           | Johan   | Doe
2           | Monique | Patricks

Orders
id_order  | client_id 
1001      | 1         
1002      | 1         
1003      | 2         

Order_lines
id_oline | id_order | id_product
1        | 1001     | 13
2        | 1001     | 21
3        | 1001     | 312
4        | 1002     | 33
5        | 1003     | 41
5        | 1003     | 11

我可以做所有简单的查询,但我需要更难一点,这给了我想要的结果:

QUERY RESULT
client_id  | name     | lastname    | Num_products (Count rows)
1          | Johan    | Doe         | 4
2          | Monique  | Patricks    | 2

我甚至不知道从哪里开始......任何帮助都会被预先确定

4 个答案:

答案 0 :(得分:1)

http://sqlfiddle.com/#!9/af49f1/1

SELECT c.client_id, c.name, c.lastname, 
       count(DISTINCT order_lines.id_product) as Num_Products
FROM Clients c
LEFT JOIN Orders o
ON c.client_id = o.client_id
LEFT JOIN Order_Lines 
ON o.id_order = Order_Lines.id_order
GROUP BY c.client_id

答案 1 :(得分:0)

为此,您将聚合与GROUP BY子句一起使用:

SELECT client_id, name, lastname, count(order_lines.id_oline) as Num_Products
FROM Clients
    INNER JOIN Orders on clients.client_id = orders.order_id
    INNER JOIN Order_Lines on Orders.id_order = Order_Lines.id_order
GROUP BY client_id, name, lastname

答案 2 :(得分:0)

此代码完全未经测试,但它应该完全符合您的需要。我建议你阅读group by statements

希望这有帮助!

SELECT c.client_id, c.name, c.lastname, COUNT(*)
FROM Clients AS c
    INNER JOIN Orders AS o ON c.client_id = o.client_id
    INNER JOIN Order_lines AS ol ON o.id_order = ol.id_order
GROUP BY c.client_id, c.name, c.lastname;

答案 3 :(得分:0)

float("67.65 GB".split()[0]) > 120