加入时棘手的SQL

时间:2010-03-27 23:44:56

标签: sql mysql

我有两个表,节目和对象。我想打印出最新的对象,以及它们的显示名称。现在我这样做:

SELECT MAX(objects.id) as max_id, shows.name, shows.id 
FROM shows, objects 
WHERE shows.id = objects.showId
GROUP BY shows.name 

但是,如果我还想获取对象的剧集我不能像SELECT object.episode [...]那样,因为那时候不会自动选择MAX(objects.id)的对象,所以我的问题是怎么做?

如果你还没有找到我的表,他们会是这样的:

  • 节目
    • 编号
    • 名称

还有:

  • 物件
    • 编号
    • 名称
    • showId

使用MySQL。

3 个答案:

答案 0 :(得分:1)

像这样(未经测试):

SELECT objects.id as max_id, objects.episode, shows.name, shows.id
  FROM shows, objects 
 WHERE shows.id = objects.showId
   AND objects.id = (
        SELECT MAX(id) FROM objects
         WHERE name = shows.name
       )

答案 1 :(得分:0)

SELECT objects.id as max_id, shows.name, shows.id 
FROM shows, objects 
WHERE shows.id = objects.showId
ORDER BY objects.id DESC
GROUP BY shows.name 
LIMIT 1

这样做你需要的吗?

答案 2 :(得分:0)

我觉得这样的事情也会起作用:

SELECT objects.id, objects.episode, shows.name, shows.id 
FROM shows 
JOIN objects AS objects_for_max ON shows.id = objects.showId
JOIN objects ON objects.id=MAX(objects_for_max.id)
GROUP BY shows.name