0

我有表 gall_photos,其中包含许多画廊的照片

  • 标识(整数)
  • gall_id (int)
  • 文件名(varchar)
  • 位置(整数)
  • 预览 (tinyint 1)
  • date_add(日期时间)

现在我想获取照片列表(用于摘要预览),每个gal_id之一,但如果有预览1,那么这个,否则是位置​​编号最低的照片。最后按 date_add 排序

select * 
from gall_photos 
where (preview = 1 or position = min(position)) 
group by gall_id 
order by date_add

此查询返回错误(如果使用“或 position = min(position)”)

请问,有什么想法吗?

编辑(12.1. 18:50UTC):可以在一个画廊(gall_id)中检查更多照片的预览,然后我需要其中一张,再次是最低位置

4

5 回答 5

1

你可以这样做

select * 
from gall_photos x 
where (preview = 1 or (position = 
                             (SELECT min(x2.position)
                              FROM gall_photos x2 
                              WHERE x.gall_id = x2.gall_id
                              Group By x2.gall_id)
                      and not exists 
                              (select 1 
                               from gall_photos x2 
                               where x2.gall_id=x.gall_id 
                               and x2.preview=1)
                        )
       );

SQL 小提琴演示

于 2013-01-11T17:20:49.380 回答
0
select id, gall_id, filename, position, preview, date_add
from gall_photos 
where position in (select min(position)from gall_photos) 
or
exists (select preview from gall_photos where preview = 1)
group by gall_id
order by date_add;
于 2013-01-11T17:35:26.623 回答
0

rs 的解决方案非常接近,但是如果您有一条 preview=1 的记录,并且它没有 gall_id 的最低位置,他会给您 preview=1 和最低位置。所以我认为你想要的是:

select * 
from gall_photos g1
where preview = 1
  or not exists (select * from gall_photos g2 where g2.gall_id=g1.gall_id and g2.preview=1)
  and position = (select min(g3.position) from gall_photos g3
    where g3.gall_id=g1.gall_id)
order by date_add
于 2013-01-11T17:46:33.973 回答
0

像这样的东西怎么样...

SELECT a.gall_id
     , COALESCE(c.position,a.position) position
  FROM gall_photos a
  JOIN 
     ( SELECT gall_id,MIN(position) min_position FROM gall_photos GROUP BY gall_id) b 
    ON b.gall_id = a.gall_id 
   AND b.min_position = a.position
  LEFT
  JOIN gall_photos c
    ON c.gall_id = a.gall_id
   AND c.preview = 1;
于 2013-01-11T17:52:06.273 回答
0

WHERE CLAUSE不允许与GROUP BY

使用HAVING

select * 
from gall_photos 
group by gall_id 
having (preview = 1 or position = min(position)) 
order by date_add
于 2013-01-11T19:18:49.533 回答