查询连接表中的单行和已连接表的总计数

时间:2016-12-09 06:30:21

标签: sql

stackoverflow社区。 我用SQL语句介绍了一个问题,我希望你能帮助我。

我有两个表:accountsusersusers引用accountsaccount_id。 我想要做的是让以下查询工作:

`SELECT accounts.*, count(users.*), user.* 
 FROM accounts
 INNER JOIN users on accounts.id = users.account_id
 INNER JOIN users user on accounts.id = user.account_id limit 1
 GROUP BY accounts.id`

所以,我会得到以下结果

`| accounts.id  | users_count | user.phone |
 ===========================================
 |     1        |      5      |  xxxxxx    |

基本上,我想获得帐户内所有用户的数量以及单个用户的特定数据。甚至可以在单个查询中进行吗?

感谢您对答案的要求。

4 个答案:

答案 0 :(得分:0)

假设您希望每个用户和帐户都有一行,您可以执行以下操作:

SELECT accounts.id,usercount.usercount,users.phone
FROM accounts 
INNER JOIN users 
ON accounts.id = users.account_id
INNER JOIN(
  SELECT count(*) usercount,users.account_id
  FROM users
  GROUP BY account_id
) usercount
on usercount.account_id = accounts.id

如果您想要帐户中任何单个用户的数据,您可以使用获取MAX(users.id)获取帐户的任何用户,然后在结果中获取该用户的数据。

SELECT accounts.id,usercount.usercount,users.phone
FROM accounts
INNER JOIN(
  SELECT count(*) usercount,users.account_id,MAX(users.id) as userid
  FROM users
  GROUP BY account_id
) usercount
on usercount.account_id = accounts.id
INNER JOIN users 
ON accounts.id = users.account_id AND usercount.userid = users.id

答案 1 :(得分:0)

如果您使用的是SQL-server,可以尝试使用注释。

SELECT src.*, user.*, userCount.cnt  FROM (SELECT DISTINCT id from accounts)src INNER JOIN
user ON src.id = user1.account_id
CROSS APPLY 
(SELECT COUNT(1) AS cnt FROM users WHERE account_id = src.id) userCount

按accounts.id分组是没有意义的,否则你永远不能拥有用户的所有行。你可以用accounts.id和用户的其他字段进行分组,但最终你没有正确的行数。

如果您的account_id在帐户表中重复,则需要在开头区分它(在此示例中,它只是不同的和获取的ID,您可能需要区分更多列。)

答案 2 :(得分:0)

您可以使用:

SELECT      D1.id, D2.phone,
           (Select Count(*) From Users D3 where D3.account_id = D1.id)  as cnt
FROM       Accounts D1
INNER JOIN Users  D2
  ON       D1.id = D2.account_id

答案 3 :(得分:0)

试试这个..

    SELECT t.*,
    (SELECT s.* FROM users AS s WHERE s.account_id = t.id LIMIT 1)
    FROM
    (
        SELECT a.*, COUNT(u.*) AS user_count
           FROM accounts AS a INNER JOIN users AS u ON a.id = u.account_id
           GROUP BY u.id
    ) AS t;