数据库查询以获取最近更新的实体

时间:2012-03-20 03:42:21

标签: mysql database join relationship

我在MySQL数据库中有两个表 -

/* main theatre table */
CREATE TABLE THEATRE 
(
id VARCHAR(100) PRIMARY KEY,
name VARCHAR(100) NOT NULL,
location VARCHAR(100),
type VARCHAR(100), /* comma separated values */ 
createDateTime BIGINT NOT NULL /* Current time in milliseconds everytime a record is inserted */
);


/* table to capture all theatre activity */
CREATE TABLE THEATRE_ACTIVITY
(
id VARCHAR(100) PRIMARY KEY,
theatreId VARCHAR(100) NOT NULL REFERENCES THEATRE(id),
activity VARCHAR(20), /* (RATED | CREATED | EDITED) */
createDateTime BIGINT NOT NULL /* Current time in milliseconds everytime a record is inserted */
);

每次THEATRE中有活动时,都会在T HEATRE_ACTIVITY表中插入记录。我需要根据distinct THEATRE从最近到最后获取所有THEATRE_ACTIVITY个所有createDateTime个名称,ID和位置。

有人可以帮帮我吗?

3 个答案:

答案 0 :(得分:0)

select id, name, location
from theatre  INNER JOIN 
(select theatreid, MAX(createDateTime)
from theatre_activity
group by theatreId) ta ON theatre.id = ta.theatreId

该查询将获取所有具有影院活动的不同影院(假设影院桌中没有重复影片)。 如果有多个活动,则选择最近的活动。这是我从你的问题陈述中理解的。

答案 1 :(得分:0)

我提供了一个查询,我从您的问题陈述中理解了这一点。

select DISTINCT t.id, t.name, t.location from theatre t, theatre_activity ta where t.id = ta.theatreId order by t.id desc

答案 2 :(得分:0)

尝试此查询

select id, name, location, ta.td
from theatre  INNER JOIN 
(select theatreid, MAX(createDateTime) td
from theatre_activity
group by theatreId  ) ta ON theatre.id = ta.theatreId  order by ta.td desc