mySQL查询 - 如果连接表中的最新记录包含特定值,请选择连接

时间:2013-12-15 00:25:12

标签: mysql sql join

我正在尝试使用右连接(到客户端)编写一个select语句,它将在连接表中找到一个特定的值 - 但是,如果这是每个客户端的最新值(忽略空格和空值)。

  Clients
  Id    Name
   0     John Doe
   1     Frank Smith
   2     Sue Smith
   3     John Smith


 Activity   (join table)
 ClientId  Type   Date
   0       500   2013-01-01 00:00:08
   1       900   2013-01-01 00:00:07
   2       NULL  2013-01-01 00:00:06
   3             2013-01-01 00:00:05
   4       500   2013-01-01 00:00:05
   0       800   2013-01-01 00:00:04
   1       500   2013-01-01 00:00:03
   2       500   2013-01-01 00:00:02
   3       500   2013-01-01 00:00:01
   4       800   2013-01-01 00:00:00

所以这个查询至少只会给我一个活动类型为500的客户端记录(在这种情况下我会回到客户端0和4):

select * from clients right join activity on activity.clientid = clients.id 
where activity.type = 500

但是,我需要弄清楚如何只返回上述记录列表中的第一条记录。客户端#0是唯一具有500的客户端,因为它的最新活动类型= 500.其他3个客户端具有NULL,空白或900,例如作为其“最新”活动类型。

我正在考虑订购的一些魔力(日期通常非常准确),“顶部”和/或“限制”以及可能的联合?只是不能完全绕过它。

3 个答案:

答案 0 :(得分:0)

请试试这个

SELECT activity.id AS activityid
    , activity.type
    , activity.date
    , clients.id AS clientid
    , clients.name
FROM activity
LEFT JOIN activity AS other_activities
  ON activity.ClientID  = other_activities.ClientID
    AND activity.date < other_activities.date
LEFT JOIN clients
  ON activity.ClientID = clients.id
WHERE activity.type = 500
  AND other_activities.ClientID IS NULL;

答案 1 :(得分:0)

这将为您提供最新的500型活动和该活动的客户

SELECT * FROM
    (SELECT *
     FROM activity
     WHERE type=500
     ORDER BY date DESC
     LIMIT 1) a
LEFT JOIN
     clients c
ON (a.clientid = c.id)

如果您只想要结果,如果它是最近的活动且类型是500,您可以使用

SELECT * FROM
    (SELECT *
     FROM activity
     ORDER BY date DESC
     LIMIT 1) a
LEFT JOIN
     clients c
ON (a.clientid = c.id)
WHERE a.type = 500;

sqlFiddle here获取最新活动类型为500的客户

SELECT a1.ClientID,c.name,a1.Type,a1.Date
FROM activity a1
LEFT JOIN clients c ON (c.id = a1.clientid)
WHERE NOT EXISTS (SELECT 1
                  FROM activity a
                  WHERE a.clientid = a1.clientid
                    and a.date > a1.date)
AND a1.type = 500;

答案 2 :(得分:0)

SELECT * from Activity 
INNER JOIN (SELECT MIN(Date) as min_date, clientID 
    FROM Activity 
    GROUP BY clientID) temp 
ON Activity.clientID = temp.clientID 
WHERE date = min_date and type = 500

这将返回最近活动类型为500的所有clientID。