在每个中选择第一个(SQL / PHP)

时间:2011-02-28 20:09:18

标签: php mysql

好的,我试着推迟并寻找答案,但我需要你们的帮助!我有三个表 - 类别,项目和图像。我已将其设置为将图像链接到特定项目,并且每个项目都有一个类别。我使用两个内部联接来做到这一点(这是正确的吗?)我最终要做的是让PHP回显每个项目的第一个图像,然后我将使用ajax加载其余的图像项目。我看过LIMIT,我确信有一种方法可以轻松地使用PHP和for循环,但我只是难倒!我怎样才能回显每个项目的第一个“文件名”?提前谢谢!

表:

CREATE TABLE `category` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

CREATE TABLE `project` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `caption` text NOT NULL,
  `category` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

CREATE TABLE `images` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `filename` varchar(255) NOT NULL,
  `project` int(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;

查询:

SELECT i.filename as filename,
          i.project as project_id,
          p.name as project_name,
          c.name as category

FROM images i

INNER JOIN project p
ON i.project = p.id

INNER JOIN category c
ON p.category = c.id

4 个答案:

答案 0 :(得分:2)

通常,您可以按特定列/列对查询结果进行分组。

没有GROUP BY的查询更适合在项目中查找第一个图像:

SELECT @pid := `prj_id`, 
   (SELECT MIN(`id`) FROM `images` `i` WHERE `i`.`prj_id` = @pid) `first_img`
FROM `projects`

这也将选择根本没有图像的项目(即first_imgNULL)。可能需要过滤这些子句HAVING

答案 1 :(得分:1)

在某些时候尝试DISTINCT:

SELECT i.filename as filename,
          i.project as project_id,
          DISTINCT(p.name) as project_name,
          c.name as category

FROM images i

INNER JOIN project p
ON i.project = p.id

INNER JOIN category c
ON p.category = c.id

答案 2 :(得分:1)

我认为这只适用于MySQL,每个项目会给你一个(随机)文件名:

SELECT i.filename as filename
     , i.project as project_id
     , p.name as project_name
     , c.name as category

  FROM images i
    INNER JOIN project p
      ON i.project = p.id
    INNER JOIN category c
      ON p.category = c.id

  GROUP BY p.id
;

这将选择ID最低的文件名。我相信它可以在性能方面得到改善。我绝对需要一些睡眠......

SELECT i.filename as filename
     , im.project_id
     , im.project_name
     , im.category

  FROM images i
    INNER JOIN 
    ( SELECT MIN(i.id) as id
           , i.project as project_id
           , p.name as project_name
           , c.name as category
        FROM images i
          INNER JOIN project p
            ON i.project = p.id
          INNER JOIN category c
            ON p.category = c.id
        GROUP BY p.id
    ) AS im
    ON i.id= im.id
;

答案 3 :(得分:-1)

您可以使用:

foreach ($Result as $r)
{
echo $r['picture'];
break;
}

但那不会很好。你应该在SQL中使用LIMIT,LIMIT有什么问题吗?