簡體   English   中英

Esqueleto / raw SQL —是否按另一個表的排序結果對查詢進行排序?

[英]Esqueleto/raw SQL — Sorting a query by the result of a sort on another table?

實際上,我對SQL的工作方式有些陌生-我總是讓ORM替我處理一切。 但是在這種情況下,Persistent不會公開這種功能,所以我迷失了該做什么。

我有多對多關系:

+------------+
| Entries    |
+----+-------+
| id | date  |
+----+-------+
| 1  | Jan 1 |
+----+-------+
| 2  | Jan 2 |
+----+-------+
| 3  | Jan 3 |
+----+-------+

+------------+
| Tags       |
+------------+
| id | label |
+----+-------+
| 1  | Apple |
+----+-------+
| 2  | Boat  |
+----+-------+
| 3  | Car   |
+----+-------+

+-------------------+
| EntryTags         |
+----------+--------+
| entry_id | tag_id |
+----------+--------+
| 1        | 1      |
+----------+--------+
| 1        | 2      |
+----------+--------+
| 2        | 2      |
+----------+--------+
| 3        | 3      |
+----------+--------+

我想首先按標簽的最新輸入日期(降序)對標簽進行排序,其次按標簽的標簽(升序)進行排序。

Tag Car的最新條目是1月3日,因此排名第一。 標簽Apple的最新的條目是1月2日,但這樣的標簽Boat 但是,標簽Apple按字母順序在標簽Boat之前,因此Apple是2nd,而Boat是3rd:

returns:
1. Tag w/ id 3
2. Tag w/ id 1
3. Tag w/ id 2

通過我的研究,我發現我需要某種形式的連接來做到這一點。 但是到目前為止,我只發現了一對多關系(按主題的最新帖子對主題進行排序),我認為我理解它們,但是沒有涉及到多對多關系的三向聯接關系。

我將原始sql作為可能的答案,因為我認為我實際上只是在尋求sql的方式,即使我將Esqueleto用於SQL綁定,我也認為一旦我了解了SQL,翻譯成Esqueleto很簡單。 我將postgresql用作后端,但我不希望使用postgres專用的東西,因為我的綁定是針對通用后端的。

有人知道我可以從哪里開始嗎? 我應該查看哪種聯接,如何對最新的聯接進行排序?

另一個解決方案:

select t.id as tag_id, t.label as tag, max(date) as date from Tags t
join EntryTags et on t.id=et.tag_id
join Entries e on e.id=et.entry_id
group by t.label,t.id
order by date desc,tag

返回:

tag_id  tag    date   
------  -----  -----  
1       Apple  jan 3  
3       Car    jan 3  
2       Boat   jan 2  

(在您的數據中,Apple的最新條目是1月3日,而不是1月2日。)

Postgres中的聯接是隱式的“內部聯接”。 如果您可能有沒有條目的標簽,則需要將聯接更改為左聯接。

SQL小提琴

您的樣本數據不適合文本。 表條目標記應為

(1, 1),
(1, 2),
(2, 2),
(2, 1),
(3, 3);

select id, label
from (
    select distinct on (t.id) e.date, t.label, t.id
    from
        entries e
        inner join
        entrytags et on et.entry_id = e.id
        inner join
        tags t on t.id = et.tag_id
    order by t.id, e.date desc, t.label
) s
order by "date" desc, label

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM