好吧,我一直在使用MySQL这么久以至于我忘记了它比MS SQL更容易使用。我在应该是一个简单的嵌套查询时遇到问题。
我有两个表,组和group_members。
我正在尝试使用groups.id作为子查询参数从group_members中选择组中的数据和记录计数。
以下是我正在使用的查询:
SELECT id AS [Group ID],
type,
name,
(SELECT COUNT(1) FROM group_members WHERE (group_id = [Group ID]) AND (paid = 1)) + '/' + (SELECT COUNT(1) FROM group_members WHERE (group_id = [Group ID]))
FROM groups
对于每个小组,这将显示类型,名称以及以分数形式支付的人数(即“6/10”)。
当我在SQL CE中尝试使用此查询时,我收到一条错误:“解析查询时出错。”
如果我单独运行查询它们工作正常,所以我猜测SQL CE处理嵌套查询与MySQL方法的方式存在问题。
任何建议都会非常感激!
答案 0 :(得分:2)
对于任何感兴趣的人,我终于能够通过执行子查询的左连接而不是在主SELECT语句中调用它来实现此目的。
以下是工作查询:
SELECT grps.group_name,
CASE
WHEN members1.paid_count IS NULL
THEN 0
ELSE members1.paid_count
END AS paid,
CASE
WHEN members2.member_count IS NULL
THEN 0
ELSE members2.member_count
END AS total_members
FROM groups AS grps
LEFT JOIN (SELECT group_id, COUNT(id) AS paid_count FROM group_members WHERE paid = 1 GROUP BY group_id) AS members1 ON grps.id = members1.group_id
LEFT JOIN (SELECT group_id, COUNT(id) AS member_count FROM group_members GROUP BY group_id) AS members2 ON grps.id = members2.group_id