限制加入查询和订单的结果

时间:2017-05-13 07:28:56

标签: mysql sql

我有这个查询

<div class = "movies">
<a href = " This text is fixed "><img src = "This is a text/media/poster.png" alt = "This is a text"><hr color = "blue" size = "3"><font><center>This is a Text</center></font></a>
</div>

此查询的结果为image_1

我想加入它

  

ORDER BY b。select a.*, GROUP_CONCAT(b.`filename`) as `filesnames` from `school_classes` a join classes_data.`classes_albums` b on a.`school_key` = b.`school_key` and a.`class_key` = b.`class_key` group by a.`ID` DESC LIMIT 2

所以filenames列的输出只显示最新的2个文件,?

1 个答案:

答案 0 :(得分:0)

从您的问题中不清楚您的表格是什么样的以及它们之间的关系,但这可能就是您所追求的。

drop table if exists school_classes;
   create table school_classes (id int,school_key int, class_key int);
   drop table if exists classes_albums;
   create table classes_albums(id int,school_key int, class_key int, filename varchar(3),dateadded date);

   insert into school_classes values
   (1,1,1), (2,1,2),(3,1,3)

   insert into classes_albums values
   (1,1,1,'a','2017-01-01'),(1,1,1,'b','2017-02-01'),(1,1,1,'c','2017-03-01');

    select a.*, b.filenames
    from school_classes a
    join
    (   
    select c.school_key,c.class_key,group_concat(c.filename order by c.rn desc) filenames
    from
    (
    select c.*,
            if(concat(c.school_key,c.class_key) <> @p, @rn:=1, @rn:=@rn+1) rn,
            @p:=concat(c.school_key,c.class_key) p 
    from classes_albums c, (select @rn:=0, @ck:=0,@sk:=0) rn
    order by c.school_key,c.class_key, c.dateadded desc
    ) c
    where c.rn < 3
    group by c.school_key,c.class_key
    ) b on b.school_key = a.school_key and b.class_key = a.class_key

+------+------------+-----------+-----------+
| id   | school_key | class_key | filenames |
+------+------------+-----------+-----------+
|    1 |          1 |         1 | b,c       |
+------+------------+-----------+-----------+
1 row in set (0.02 sec)