您好我有两张桌子 a2_deal (我没有提到整张桌子非常大)
deviceID companyID stage serverTime
1 14 -1 1349449200
1 1 -1 1349445600
2 21 -1 1349449200
3 17 -1 1349447160
1 14 3 1344449200
1 14 2 1340449200
和另一个名为 a2_comp
的表格companyID name
1 Microsoft
14 DELL
15 APPLE
17 Google
我正在尝试使用以下查询来获取公司的最新阶段:
SELECT deal.companyID, companies.name as Company,
if(max(serverTime),stage,Null) as Stage
FROM `a2_deal` AS deal
LEFT JOIN `a2_comp` AS companies ON deal.companyID = companies.companyID
GROUP BY companyID
ORDER BY serverTime
在我的查询中我使用 if(max(serverTime),stage,Null)作为Stage ,这意味着选择与最近服务器时间相关的阶段值。即它应该给我-1作为公司ID 14的阶段....但由于某种原因我没有得到正确的输出..请解释我的逻辑错误在这里...谢谢
答案 0 :(得分:1)
SELECT a2_comp.*, a2_deal.*
FROM a2_deal NATURAL JOIN (
SELECT companyID, MAX(serverTime) AS serverTime
FROM a2_deal
GROUP BY companyID
) t JOIN a2_comp USING (companyID)
在sqlfiddle上查看。
答案 1 :(得分:0)
case
用于查询中的内联条件。此外,您可能需要
(case when max(serverTime) = serverTime then stage else null end) as Stage
我不完全确定这是有效的,但你可以尝试一下。
答案 2 :(得分:0)
试试这个
SELECT deal.companyID, deal.stage, comp.name
FROM a2_deal AS deal, a2_comp AS comp
WHERE deal.serverTime =
(SELECT MAX(deal2.serverTime)
FROM a2_deal AS deal2
WHERE deal2.companyID = deal.companyID)
AND comp.companyID = deal.companyID
GROUP BY deal.companyID
这可能有点令人困惑,但最有趣的部分是为每个公司选择最近的serverTime的子查询。我使用了theta样式查询,因此不需要JOIN。