如何编写一个sql语句来获取所有用户的值?

时间:2013-06-09 06:58:24

标签: mysql sql

我有一个像这样的SQL语句

select users.id, users.username, count(orders.number) as units from users inner join orders on orders.user_id = users.id where users.id = 1;

现在这将是用户ID的数量或单位。

如何获取所有用户以及他们购买的数量或单位。 where关键字需要一个值和一个特定的值,我怎么能说所有用户。

非常感谢您阅读此内容:)

3 个答案:

答案 0 :(得分:3)

您应该使用GROUP BY

     SELECT users.id, users.username, count(orders.number) as units 
     FROM users 
     INNER JOIN orders on orders.user_id = users.id 
     GROUP BY users.id, users.username

您可以在此处查看更多内容:GROUP BY (Aggregate) Functions

答案 1 :(得分:2)

您需要聚合数据,为此请使用GROUP BY

        SELECT
        users.id, 
        users.username,
        count(orders.number) as units 
        FROM users  
        JOIN orders 
        ON orders.user_id = users.id
        GROUP BY users.id, users.username;

查看此处的documentation

答案 2 :(得分:1)

如果您需要所有用户,请删除where子句并按用户ID分组

select users.id, users.username, count(orders.number) as units 
from users inner join orders 
on orders.user_id = users.id 
group by users.id,users.username;