SQL从表A中选择所有计数表B

时间:2011-04-13 02:55:45

标签: sql

如果我需要一个查询,以便从表A中获取所有列,但我还需要计算表A中每行的B数。

表A:id | username | email | address

表B:user_id

SELECT *, total 
  FROM table_a 
 WHERE total = (SELECT * FROM table_b WHERE table_a.id==table_b.user_id)

有什么想法吗?

编辑:有关详细说明,请参阅所需的输出

1 | steve | steve@steve.steve | 123 Steve | 5 // letters
2 | chris | chris@chris.chris | 123 chris | 2 // letters

4 个答案:

答案 0 :(得分:2)

SELECT 
     table_a.id, 
     table_a.username, 
     table_a.email, 
     table_a.address, 
     count(table_b.user_id) as total
 FROM table_a 
          LEFT OUTER JOIN table_b 
             ON table_a.id = table_b.user_id
  GROUP BY (
              table_a.id, 
              table_a.username, 
              table_a.email, 
              table_a.address
           )

这是需要外部加入的一个很好的例子。如果我们使用内部连接,查询将排除 table_a 中具有零 table_b 条目的条目。

这可以进一步完善以应对两个挑战:

  • 包含 table_a 的所有列,而不明确要求它们。
  • 处理零条目场景而不使用非标准SQL(例如ISNULL,WHERE)

下面的代码应该这样做。

SELECT
     table_a.*, 
     tempTable.total
FROM (
       SELECT
           table_a.Id,
           COUNT(table_b.user_id) as total
       FROM table_a
          LEFT OUTER JOIN table_b 
             ON table_a.id = table_b.user_id
        GROUP BY (table_a.id)
     ) AS tempTable
INNER JOIN table_a 
     ON tempTable.Id = table_a.Id;

将此与Cybernate's solution进行比较,非标准SQL看起来非常有吸引力: - )

答案 1 :(得分:1)

试试这个:

SELECT a.*, ISNULL(bcnt, 0) bcnt
  FROM TableA a LEFT JOIN
     (
      SELECT user_id, COUNT(1) AS BCNT
        FROM TableB
       GROUP BY user_id
     ) b
ON a.id = b.user_id

答案 2 :(得分:0)

您可以使用LEFT JOINAGGREGATION函数

SELECT  b.user_id,
        min(a.username) UserName,
        min(a.email) Email,
        min(a.address) Address,
        COUNT(*) Quantity
  FROM  table_b b left join
        table_a a on a.id=b.user_id
group by b.user_id

答案 3 :(得分:0)

select 
  *,
  (select count(*)
   from @TableB as B
   where A.id = B.user_id) as total
from @TableA as A