1

嗨,我有两张桌子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作为companyID 14的阶段....但是由于某种原因我没有得到正确的输出..请解释我的逻辑在这里是怎么错的...谢谢

4

3 回答 3

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上查看。

于 2012-10-12T16:27:28.473 回答
0

case用于查询中的内联条件。此外,您可能需要做

(case when max(serverTime) = serverTime then stage else null end) as Stage

我不完全确定这是否有效,但您可以尝试一下。

于 2012-10-12T16:27:11.803 回答
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

这可能有点令人困惑,但最有趣的部分是为每个公司选择最近的服务器时间的子查询。我使用了 theta 样式查询,因此不需要 JOIN。

于 2012-10-12T17:47:43.540 回答