a table
a_id a_value
1 text1
2 test2
b table
b_id b_num a_id
1 5 1
2 7 1
3 2 1
4 7 2
5 56 2
结果基于一个表(已编辑)
a_id:1 a_value:text1 total:3条记录
a_id:2 a_value:text2 total:2条记录
如何在sql中获取此格式?
查询表并在表b中添加字段(总计)b.a_id = a.a_id
谢谢..答案 0 :(得分:0)
我想你的b表中有错误,所以我会假设你所谓的b_id
实际上是a_id
,或者你的结果是错误的
无论如何你可以使用:
SELECT COUNT(b.a_id) AS total FROM b GROUP BY (SELECT a.a_id FROM a)
ORDER BY b.a_id
答案 1 :(得分:0)
基于问题更改的更新查询
SELECT a_id, a_value, x.total
FROM a
INNER JOIN
(SELECT b.a_id, COUNT(1) AS total
FROM b
GROUP BY (b.a_id)) X
ON a.a_id = x.a_id
ORDER BY a.a_id
答案 2 :(得分:0)
您可以尝试:
SELECT a.a_id AS id, a.a_value AS value, (SELECT count(b.b_id) AS count FROM b WHERE (b.a_id = a.a_id)) AS total FROM a GROUP BY a.a_id
然后使用表格 a 和 b 中的数据显示示例的结果:
**id value total**
1 text1 3
2 text2 2