1

我有以下 sql 查询

 SELECT 
(SELECT count(cid) from A where uid=45 group by cid) as cats 
(SELECT count(cid) from A where uid=45) as cats_total

第一个子选择产生 4 行并计算每个 cid 中的项目数。第二个子选择仅产生 1 行并计算项目总数。

我的问题在于第二个子选择。SQL 产生错误,因为它们具有不同数量的行。我是否可以进行调整,使第二个子选择有 4 行,或者第一个子选择产生的行数?

更新:让我用我需要制作的表格进一步澄清

+------+------------+
| cats | cats_total |
+------+------------+
|    2 |         17 |
|    5 |         17 |
|    1 |         17 |
|    9 |         17 |
+------+------------+
4

4 回答 4

0

或者,您可以使用UNION ALL,

SELECT SUM(totals) grandTotal
FROM
(
    SELECT count(cid) totals from A where uid=45 group by cid
    UNION ALL
    SELECT count(cid) totals from A where uid=45
) s
于 2013-03-13T07:42:56.123 回答
0

卡夫是对的。

如果有人对这里感兴趣的是通过 jdbc 测试到 Oracle db 的工作版本:

SELECT cats,cats_total from  
(SELECT count(cid) as cats from A where uid=45 group by cid)
cross join
(SELECT count(cid) as cats_total from A where uid=45)
于 2013-03-13T08:40:12.107 回答
0

我认为您可以对两个子查询进行交叉连接;

SELECT cats, cats_total 
FROM (SELECT count(cid) as cats from A where uid=45 group by cid) as c1 
        CROSS JOIN
     (SELECT count(cid) as cats_total from A where uid=45) as c2
于 2013-03-13T08:12:47.153 回答
0

你可以试试

SELECT cats.total, cats_total.total from 
(SELECT count(cid) as total from A where uid=45 group by cid) as cats ,
(SELECT count(cid) as total from A where uid=45) as cats_total
于 2013-03-13T08:59:39.203 回答