我已經(簡化)以下模型的每個項目的最高排名:查詢來獲取
Book
id
name
BookCategory
book_id
category_id
rank
Category
id
name
對於給定的類ID,我想獲得具有類書籍中排名最高一。
我舉個例子是關於它的更加清晰:
Book
id name
--- -------
1 On Writing
2 Zen teachings
3 Siddharta
BookCategory
book_id category_id rank
--- ------- -----
1 2 34.32
1 5 24.23
1 9 54.65
2 5 27.33
2 9 28.32
3 2 30.43
3 5 27.87
Category
id name
--- -------
2 Writing
5 Spiritual
9 Buddism
爲CATEGORY_ID結果= 2將是書ID = 3
這是我的查詢運行:
SELECT book."name" AS bookname
FROM bookcategory AS bookcat
LEFT JOIN book ON bookcat."book_id" = book."id"
LEFT JOIN category cat ON bookcat."category_id" = cat."id"
WHERE cat."id" = 2
ORDER BY bookcat."rank"
這不是正確的做法,因爲它沒有選擇每本書的最高排名。我還沒有找到合適的解決方案。
注意:我正在使用postgresql 9.1版本。
編輯:
DB模式(從馬丁的SQL小提琴回答):
create table Book (
id int,
name varchar(16)
);
insert into Book values(1, 'On Writing');
insert into Book values(2, 'Zen teachings');
insert into Book values(3, 'Siddharta');
create table BookCategory (
book_id int,
category_id int,
rank real
);
insert into BookCategory values(1,2,34.32);
insert into BookCategory values(1,5,24.23);
insert into BookCategory values(1,9,54.65);
insert into BookCategory values(2,5,27.33);
insert into BookCategory values(2,9,28.32);
insert into BookCategory values(3,2,30.43);
insert into BookCategory values(3,5,27.87);
create table Category (
id int,
name varchar(16)
);
insert into Category values(2, 'Writing');
insert into Category values(5,'Spiritual');
insert into Category values(9, 'Buddism');
如果你能證明你的例子爲表結構及數據'CREATE TABLE'和'INSERT'聲明,人們可以複製並粘貼到一個測試數據庫來嘗試解決方案之前,張貼。 – kgrittn 2012-08-08 17:14:00