简体   繁体   English

PostgreSQL查询问题

[英]Postgresql query issue

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. 现在出现了问题:我想按日期desc对行进行排序并区分它们,以便最后插入的行(具有最新的日期)是第一行。 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: 这行得通,尽管一旦我尝试了distantig a.book_fk,结果是错误的:

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! 谢谢!

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
;

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

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