如何查询3个表中的最后一个数据

时间:2015-01-14 09:12:20

标签: postgresql

现在我有3个表,例如A,B,C 它们之间的关系是A onomanomany B,B onetomany C. C是表格保存的照片 现在我想从A获取数据,但只有每张A的最后一张照片。

colomns可能是这样的:

table a:
id     a_msg
a1     msg in a
a2     msg in a
a3     msg in a

table b:
id     b_msg             a_id
b1     some data in b    a1
b2     some data in b    a1   
b3     some data in b    a2
b4     some data in b    a3


table c:
id    url           createdate                   c_msg              b_id
c1    /file/1.jpg   2014-12-01 06:55:54.600      some data in c     b1
c2    /file/2.jpg   2014-12-01 06:55:54.601      some data in c     b1
c3    /file/3.jpg   2014-12-01 06:55:54.602      some data in c     b1
c4    /file/4.jpg   2014-12-01 06:55:54.603      some data in c     b2
c5    /file/5.jpg   2014-12-01 06:55:54.604      some data in c     b2
c6    /file/6.jpg   2014-12-01 06:55:54.605      some data in c     b3

我想要的结果

c_id url           createdate                c_msg            b_msg            b_id  a_msg    a_id

c6   /file/6.jpg   2014-12-01 06:55:54.605   some data in c   some data in b   b3    msg in a  a1
c5   /file/5.jpg   2014-12-01 06:55:54.604   some data in c   some data in b   b2    msg in a  a1

抱歉,我不知道如何使用工具来描述表格,希望您能够轻松理解我的意思。

如果我的说明不够清楚,我会编辑问题,谢谢,如果有人可以帮助我

1 个答案:

答案 0 :(得分:0)

以下面的例子为例:

create table table_a (id int,a_msg text);

create table table_b (id int,b_msg text,a_id int);

create table table_c (id int,url text,createdate timestamp with time zone,c_msg text ,b_id int);

和数据

insert into table_a values (1,'msg in table_a')
                          ,(2,'2nd msg in table_a')
                          ,(3,'3rd msg in table_a');

insert into table_b values (20,'msg in table_b',1)
                          ,(21,'2nd msg in table_b',2)
                          ,(22,'3rd msg in table_b',3);

insert into table_c values (30,'url','2014-12-01 06:55:54.600','msg in table_c',20)
                           ,(31,'url 1','2014-12-01 06:55:54.604','2nd msg in            table_c',21)
                           ,(32,'url 2','2014-12-01 06:55:54.605','3rd msg in table_c',22);

获取您需要使用INNER JOIN的结果并获取最后两个数据使用order by createdate desc limit 2

 select c.id,c.url
       ,c.createdate
       ,c.c_msg,b.b_msg
       ,b.id bi_id,a.a_msg
       ,a.id a_id 
 from 
       table_c c inner join table_b b on c.b_id=b.id /* to get data from table_b */
                 inner join table_a a  on b.a_id=a.id /*  to get data from table_a */
 order by createdate desc limit 2 /*  DESC will sort from the highest date time values and LIMIT 2 will return two rows */

>SQLFIDDLE DEMO WITH OP'S DATA