繁体   English   中英

选择带有 2 个表和一个桥表的 COUNT 和 MAX 列

[英]Selecting COUNT and MAX columns with 2 tables and a bridge table

所以我想要做的是有3个表(图片,collections,和桥)与以下列:

Collections 表:

| id | name      |
------------------
| 1  | coll1     |
| 2  | coll2     |
------------------

图片表:(时间戳为 unix 时间戳)

| id | name | timestamp |
-------------------------
| 5  | Pic5 | 1         |
| 6  | Pic6 | 19        | 
| 7  | Pic7 | 3         |
| 8  | Pic8 | 892       |
| 9  | Pic9 | 4         |
-------------------------

桥表:

| id | collection | picture |
-----------------------------
| 1  | 1          | 5       |
| 2  | 1          | 6       |
| 3  | 1          | 7       |
| 4  | 1          | 8       |
| 5  | 2          | 5       |
| 6  | 2          | 9       |
| 7  | 2          | 7       |
-----------------------------

结果应该是这样的:

| collection_name | picture_count | newest_picture |
----------------------------------------------------
| coll1           | 4             | 8              |
| coll2           | 3             | 9              |
----------------------------------------------------

newest_picture应该始终是该集合中时间戳最高的图片,我也想按它对结果进行排序。 图片picture_count显然是该集合中图片的计数。

这可以在带有表连接的单个语句中完成吗?如果可以:我怎样才能以最好的方式做到这一点?

一个简单的方法使用相关子查询:

select c.*,
       (select count(*)
        from bridge b
        where b.collection = c.id
       ) as pic_count,
       (select p.id
        from bridge b join
             pictures p
             on b.picture = b.id
        where b.collection = c.id
        order by p.timestamp desc
        limit 1
       ) as most_recent_picture       
from collections c;

更常见的方法是使用 window 函数:

select c.id, c.name, count(bp.collection), bp.most_recent_picture
from collections c left join
     (select b.*,
             first_value(p.id) over (partition by b.collection order by p.timestamp desc) as most_recent_picture
      from bridge b join
           pictures p
           on b.picture = p.id
     ) bp
     on bp.collection = c.id
group by c.id, c.name, bp.most_recent_picture;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM