我有4张桌子:
这是我的查询,只有当" Total"不是0.我想返回类型" Text"的所有结果。这是我的疑问:
SELECT
MAX(RC.Text) AS Text,
MAX(RP.Text) AS TextPossibility,
COUNT(*) AS Total
FROM Request R
JOIN RequestOutcome RO ON R.RequestId = RO.Id
JOIN RequestPossibility RP ON RO.Id = RP.Id
JOIN RequestCategory RC ON RP.RequestId = RC.RequestId
GROUP BY RP.Id
ORDER BY 1, 2 ASC
答案 0 :(得分:2)
如果您计算特定字段并使用LEFT JOIN,则可以解决此问题。
SELECT
MAX(RC.Text) AS Text,
MAX(RP.Text) AS TextPossibility,
COUNT(R.RequestId) AS Total
FROM Request R
LEFT JOIN RequestOutcome RO ON R.RequestId = RO.Id
JOIN RequestPossibility RP ON RO.Id = RP.Id
JOIN RequestCategory RC ON RP.RequestId = RC.RequestId
GROUP BY RP.Id
ORDER BY 1, 2 ASC
答案 1 :(得分:0)
这就是SQL的工作原理。如果查询中没有返回任何行(COUNT(*) == 0
),则根本没有结果。
答案 2 :(得分:0)
使用LEFT JOIN:
SELECT
MAX(RC.Text) AS Text,
MAX(RP.Text) AS TextPossibility,
COUNT(*) AS Total
FROM Request R
LEFT JOIN RequestOutcome RO ON R.RequestId = RO.Id
LEFT JOIN RequestPossibility RP ON RO.Id = RP.Id
LEFT JOIN RequestCategory RC ON RP.RequestId = RC.RequestId
GROUP BY RP.Id
ORDER BY 1, 2 ASC
编辑#1:
您的问题中没有指明:" 我需要RequestPossibility.Text中的所有结果,无论其他任何表"都要返回。 检查新查询:
SELECT
RP.Text AS TextPossibility,
MAX(RC.Text) AS Text,
COUNT(*) AS Total
FROM RequestPossibility RP
LEFT JOIN Request R ON R.RequestId = RP.RequestId
LEFT JOIN RequestOutcome RO ON RP.RequestId = RO.Id
LEFT JOIN RequestCategory RC ON RP.RequestId = RC.RequestId
GROUP BY RP.Text
ORDER BY 1, 2 ASC
答案 3 :(得分:0)
使用左/右连接时,表的顺序会有所不同。 试试这个:
SELECT MAX(RC.Text) AS Text,
MAX(RP.Text) AS TextPossibility,
COUNT(*) AS Total
FROM RequestPossibility RP
LEFT JOIN Request R ON RP.id = R.RequestId
LEFT JOIN RequestOutcome RO ON R.RequestId = RO.Id
LEFT JOIN RequestCategory RC ON RP.RequestId = RC.RequestId
GROUP BY RP.Id
ORDER BY 1, 2 ASC
答案 4 :(得分:0)
你需要离开,你需要按R.RequestId(最左边)
进行分组SELECT R.RequestId,
MAX(RC.Text) AS Text,
MAX(RP.Text) AS TextPossibility,
COUNT(*) AS Total
FROM Request R
Left JOIN RequestOutcome RO
ON R.RequestId = RO.Id
left JOIN RequestPossibility RP
ON R.RequestId = RP.Id
left JOIN RequestCategory RC
ON RP.RequestId = RC.RequestId
GROUP BY R.RequestId
ORDER BY 2, 3 ASC
你在最后一次加入时翻到RequestId很奇怪 RequestId没有链接到R.RequestId
你想要RequestPossibility.Text中的所有结果然后基本查询离开了 我不清楚你真正想要的是什么
SELECT RP.Text AS TextPossibility
MAX(RC.Text) AS Text,
COUNT(*) AS Total
RequestPossibility RP
left join Request R
ON R.RequestId = RP.Id
Left JOIN RequestOutcome RO
ON RP.Id = RO.Id
left JOIN RequestCategory RC
ON RP.RequestId = RC.RequestId
GROUP BY RP.Text
ORDER BY 1, 2 ASC
答案 5 :(得分:-1)
SELECT
MAX(RC.Text) AS Text
, MAX(RP.Text) AS TextPossibility
, COUNT(R.RequestId) AS Total
FROM Request R
LEFT JOIN RequestOutcome RO ON R.RequestId = RO.RequestId
RIGHT OUTER JOIN RequestPossibility RP ON RO.Id = RP.Id
RIGHT OUTER JOIN RequestCategory RC ON RP.RequestId = RC.RequestId
GROUP BY RP.Id
ORDER BY 1, 2 ASC