0

我有 2 个表,项目/图像相关:

[project]
project_id (int primary key)
completed (date)

[project_media]
project_media_id (int primary key)
project_id (int foreign key)
image (varchar)

我要选择的是:
从基于已完成的最后5个项目记录中,取最后一个基于project_media_id添加的图像。

换句话说,从最后 5 个项目中插入的最后一个图像。

到目前为止我所拥有的:

select project.completed, project_media.project_id, project_media.image 
from project 
inner join project_media 
    on project.project_id = project_media.project_id 
order by completed desc limit 5
4

3 回答 3

0
SELECT PR.*, 
(
  SELECT PM.image FROM project_media PM
  WHERE PR.project_id = PM.project_id
  ORDER BY PM.project_media_id DESC
  LIMIT 1
) AS image
FROM 
(
  SELECT P.project_id, P.completed 
  FROM project P
  ORDER BY P.completed DESC
  LIMIT 5
) AS PR
于 2013-10-11T15:51:13.710 回答
0

如果您只想获取项目表中最近的五件事,您可以这样做:

select * from project order by completed desc limit 5;

加入另一张桌子,你最终会得到这样的结果:

select * from project p join project_media pm on p.project_id = pm.project_id order by completed desc limit 5;

限制列,您的查询将是:

select pm.image from project p join project_media pm on p.project_id = pm.project_id order by completed desc limit 5;

我有点不清楚你最后问的是什么,但听起来你现在只想从这五件事中获得一个基于 media_project_id 的图像。您可以使用子查询来执行此操作:

select a.image from (select pm.image, pm.project_media_id from project p join project_media pm on p.project_id = pm.project_id order by completed desc limit 5) a order by a.project_media_id limit 1;

这回答了你的问题了吗?

于 2013-10-11T15:52:34.757 回答
0
SELECT PM2.image
FROM
(
  SELECT
      P.project_id,
      MAX(PM.project_media_id) AS last_project_media
  FROM project_media PM
    JOIN project P ON P.project_id = PM.project_id
  GROUP BY PM.project_id
  ORDER BY PM.completed DESC
  LIMIT 5
) PM1
JOIN project_media PM2
    ON PM1.last_project_media = PM2.project_media_id
于 2013-10-11T15:56:21.350 回答