使用该表的最大主键加入表的外键

时间:2016-02-01 09:17:19

标签: mysql sql join max inner-join

我有一张工人桌和一张事件表。

Workers.ID = Events.WorkerID。我需要在查询中加入这些表,但我需要在事件表的MAX(ID)上执行此操作。我无法弄清楚如何做到这一点。

我的基础尝试:

SELECT ID, Fname, SName
FROM workers w inner join `events`on w.ID = Events.workerID.

现在,这给了我多个实例,其中workerid存在于事件表中

CREATE TABLE IF NOT EXISTS `workers` (
  `ID` varchar(20) NOT NULL,
  `Title` varchar(3) NOT NULL,
  `FName` varchar(25) NOT NULL,
  `Sname` varchar(25) NOT NULL,
  `Email` varchar(250) NOT NULL,
  `Pass` varchar(50) NOT NULL,
  `Birthday` bigint(20) NOT NULL,
  `Address` varchar(300) NOT NULL,
  `Phone` varchar(50) NOT NULL,
  `companyID` int(11) NOT NULL,
  `isAvailable` tinyint(4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `events` (
`ID` bigint(11) NOT NULL,
  `WorkerID` varchar(20) NOT NULL,
  `startLatitude` double NOT NULL,
  `startLongitude` double NOT NULL,
  `startDateTime` bigint(20) NOT NULL,
  `startLoc` varchar(200) NOT NULL,
  `Status` tinyint(4) NOT NULL,
  `isOvertime` tinyint(4) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1013 DEFAULT CHARSET=latin1;

2 个答案:

答案 0 :(得分:2)

选择按工作人员ID分组的最高事件ID ...

select max(e.ID)
from events e
group by e.WorkerID

...并将结果事件ID与工作表

连接起来
select *
from (
  select e.WorkerID, max(e.ID)
  from events e
  group by e.WorkerID
) as max_e
inner join workers w on max_e.WorkerID = w.ID

答案 1 :(得分:1)

试试这个:

SELECT t1.`Date`, t1.voucher_id, t1.person_id, 
       COUNT(t2.person_id) AS count_till_now
FROM mytable AS t1
LEFT JOIN mytable AS t2 ON t1.person_id = t2.person_id AND t1.`Date` > t2.`Date`
WHERE t1.voucher_id IS NOT NULL
GROUP BY t1.`Date`, t1.voucher_id, t1.person_id

希望这个帮助;)