douba4824 2016-03-21 18:25
浏览 13

Postgresql查询问题

so I have a problem that I'm trying to resolve since a couple of weeks, but I'm not coming to any solution. So here are the tables that I'm trying to make a query on: Tables

I obviously joined them (easy):

SELECT a.date,b.title,b.author,u.nick
FROM book_add a 
INNER JOIN user u on(a.user_fk=u.id) 
INNER JOIN book b on (a.book_fk=b.id) 
INNER JOIN status s ON(a.status_fk=s.id) 
WHERE s.description='active';

Now here comes the problem: I want to order the rows by date desc and distinct them, so that the last inserted row (with the newest date) the first row is. But results are very odd once they get distincted. I tried this:

SELECT a.date,b.title,b.author,u.nick
FROM book_add a 
INNER JOIN user u on(a.user_fk=u.id) 
INNER JOIN book b on (a.book_fk=b.id) 
INNER JOIN status s ON(a.status_fk=s.id) 
WHERE s.description='active' ORDER BY a.date DESC;

this works, though once i try distinctig a.book_fk results are wrong:

SELECT DISTINCT ON(a.book_fk)a.book_fk,a.date,b.title,b.author,u.nick
FROM book_add a 
INNER JOIN user u on(a.user_fk=u.id) 
INNER JOIN book b on (a.book_fk=b.id) 
INNER JOIN status s ON(a.status_fk=s.id) 
WHERE s.description='active' ORDER BY a.date DESC;

I even tried approaches like this one, but without success:

SELECT * FROM (SELECT DISTINCT  
ON(a.book_fk)a.book_fk,a.date,b.title,b.author,u.nick
FROM book_add a
INNER JOIN user u on(a.user_fk=u.id) 
INNER JOIN book b on (a.book_fk=b.id) 
INNER JOIN status s ON(a.status_fk=s.id) 
WHERE s.description='active') res ORDER BY res.date DESC

Could someone help me? I would be very happy! Thank you!

  • 写回答

1条回答 默认 最新

  • doukuangxiu1621 2016-03-21 18:48
    关注

    It sounds like you're trying to get one row per book, with the most recent user/status? In that case this should work:

    SELECT DISTINCT ON(a.book_fk)
           a.book_fk, a.date, b.title, b.author, u.nick
    FROM   book_add a 
    INNER JOIN user u on(a.user_fk=u.id) 
    INNER JOIN book b on (a.book_fk=b.id) 
    INNER JOIN status s ON(a.status_fk=s.id) 
    WHERE  s.description='active'
    ORDER BY a.book_fk, a.date DESC
    ;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?