我一直在尝试将来自不同表的4个或更多COUNT(*)个查询转换为一个查询。
这是可能的,还是我必须提出四种不同的查询?
这是我的代码:
try (final PreparedStatement sel = conn.prepareStatement("SELECT COUNT(*), SUM(coins) FROM User");
final PreparedStatement sel2 = conn.prepareStatement("SELECT COUNT(*) FROM Friends");
final PreparedStatement sel3 = conn.prepareStatement("SELECT COUNT(*) FROM Clans");
final PreparedStatement sel4 = conn.prepareStatement("SELECT COUNT(*) FROM ClanMembers")) {
try (final ResultSet rs = sel.executeQuery(); final ResultSet rs2 = sel2.executeQuery(); final ResultSet rs3 = sel3.executeQuery()) {
rs.last();
rs2.last();
rs3.last();
return new Object[] { rs.getInt(1), rs.getInt(2), rs2.getInt(1) / 2, rs3.getInt(1) };
}
}
答案 0 :(得分:6)
SELECT COUNT(*), SUM(coins) FROM User
union all
SELECT COUNT(*), 0 FROM Friends
union all
SELECT COUNT(*), 0 FROM Clans
union all
SELECT COUNT(*), 0 FROM ClanMembers
...
所有联合查询的列数和类型必须相同
更新答案以显示如何组合查询。
答案 1 :(得分:4)
只需提供另一个可选解决方案 (我无法评论,所以我必须写作答案)
StanislavL的回答很好,你可以使用它,它会返回(n)行
但是如果你只需要1行就可以了 你可以试试这个
SELECT q1.count1,q1.coins,q2.count2, q3.count3, q4.count4
from (select (COUNT(*) count1, SUM(coins) coins, 1 id FROM User, 1 var) q1
inner join (SELECT COUNT(*) count2, 1 id FROM Friends) q2 on q1.id=q2.id
inner join (SELECT COUNT(*) count3, 1 id FROM Clans) q3 on q1.id=q3.id
inner join (SELECT COUNT(*) count4, 1 id FROM ClanMembers) q4 on q1.id=q4.id
答案 2 :(得分:0)
好吧,似乎我错过了明显的答案。
这解决了我的问题:
appRef.queryOrderedByKey().observe(of: .childAdded, with: { (snapshot) in