SQL / PHP:每个项目只选择一行

时间:2010-08-02 17:00:31

标签: php mysql

我有一个包含人员信息的表(每人一行)和另一个包含人物照片文件名的表(每人多行)。我想选择一组人(基于另一张桌子),但每人只能选择一张照片。

我的旧SQL就像这样:

SELECT persons.personID, persons.name, persons.photo_filename, movie_cast.role
FROM persons, movie_cast
WHERE persons.personID = movie_cast.personID
AND movie_cast.imdbID = ?
ORDER BY movie_cast.castORDER
LIMIT 9';

但是在这里,'people'表还包含'photo_filename'列。在我的新数据库设计中,此列位于另一个表中。因此,如果我尝试从新表中获取photo_filename,我会获得每个人可用的所有照片,但我只需要一个。

怎么做?

1 个答案:

答案 0 :(得分:3)

在第一个例子中,我假设总有一张照片,我只是按字母顺序抓取最高排序的照片文件名,作为每次运行查询时为每个用户获取一致照片的方法。

SELECT p.personID, p.name, ph.photo_filename, mc.role 
FROM persons p
INNER JOIN movie_cast mc ON p.personID = mc.personID 
INNER JOIN (
    select personID, max(photo_filename) as MaxPhotoName
    from photos
    group by personID
) phm on p.personID = phm.personID
INNER JOIN photos ph on phm.personID = ph.personID 
    and phm.MaxPhotoName = ph.photo_filename
WHERE mc.imdbID = ? 
ORDER BY mc.cast 
LIMIT 9

如果有photo_date列,并且您想使用最新的照片,可以这样做:

SELECT p.personID, p.name, ph.photo_filename, mc.role 
FROM persons p
INNER JOIN movie_cast mc ON p.personID = mc.personID 
INNER JOIN (
    select personID, max(photo_date) as MaxPhotoDate
    from photos
    group by personID
) phm on p.personID = phm.personID
INNER JOIN photos ph on phm.personID = ph.personID 
    and phm.MaxPhotoDate = ph.photo_date
WHERE mc.imdbID = ? 
ORDER BY mc.cast 
LIMIT 9

如果没有照片,您可以使用LEFT OUTER JOIN,这样您仍然可以获得所有记录:

SELECT p.personID, p.name, ph.photo_filename, mc.role 
FROM persons p
INNER JOIN movie_cast mc ON p.personID = mc.personID 
LEFT OUTER JOIN (
    select personID, max(photo_date) as MaxPhotoDate
    from photos
    group by personID
) phm on p.personID = phm.personID
LEFT OUTER JOIN photos ph on phm.personID = ph.personID 
    and phm.MaxPhotoDate = ph.photo_date
WHERE mc.imdbID = ? 
ORDER BY mc.cast 
LIMIT 9