簡體   English   中英

在jOOQ中的DISTINCT ON()

[英]DISTINCT ON() in jOOQ

我想在PostgreSQL中進行查詢

select 
  distinct on(uuid) 
  (select nr_zew from bo_get_sip_cti_polaczenie_info(uuid)) as nr_zew 
from bo_sip_cti_event_day
where data_ins::date = current_date
and kierunek like 'P'
and (hangup_cause like 'NO_ANSWER' or hangup_cause like 'NO_USER_RESPONSE') 

在Java中,我有

Result<Record> result = create
    .select()
    .from("bo_sip_cti_event_day")
    .where("data_ins::date = current_date")
    .and("kierunek like 'P'")
    .and("(hangup_cause like 'NO_ANSWER' or hangup_cause like 'NO_USER_RESPONSE') ")
    .fetch();

它工作,但我試圖添加

Result<Record> result = create
    .selectDistinct("uuid")
    .from("bo_sip_cti_event_day")
    .where("data_ins::date = current_date")
    .and("kierunek like 'P'")
    .and("(hangup_cause like 'NO_ANSWER' or hangup_cause like 'NO_USER_RESPONSE') ")
    .fetch();

然后它說不能做selectDistinct(String). 如何在jOOQ中使用distinct?

發現這絕對不是很明顯。 選擇實際列后,有一個SelectDistinctOnStep.distinctOn()方法。 之所以發現它是不明顯的,那就是PostgreSQL語法本身在像jOOQ這樣的內部DSL中很難建模。

您可以這樣考慮:您正在選擇一組列(相關子查詢),同時指定應在哪些列上應用清晰度過濾器:

Result<Record> result = create
  .select(field("(select nr_zew from bo_get_sip_cti_polaczenie_info(uuid))").as("nr_zew"))
  .distinctOn(field("uuid"))
  .from("bo_sip_cti_event_day")
  .where("data_ins::date = current_date")
  .and("kierunek like 'P'")
  .and("(hangup_cause like 'NO_ANSWER' or hangup_cause like 'NO_USER_RESPONSE') ")
  .fetch();

或者,如果您使用代碼生成器:

Result<Record> result = create
  .select(field(
     select(BO_GET_SIP_CTI_POLACZENIE_INFO.NR_ZEW)
    .from(BO_GET_SIP_CTI_POLACZENIE_INFO.call(BO_SIP_CTI_EVENT_DAY.UUID))).as("nr_zew"))
  .distinctOn(BO_SIP_CTI_EVENT_DAY.UUID)
  .from(BO_SIP_CTI_EVENT_DAY)
  .where(BO_SIP_CTI_EVENT_DAY.cast(Date.class).eq(currentDate()))
  .and(BO_SIP_CTI_EVENT_DAY.KIERUNEK.like("P"))
  .and(BO_SIP_CTI_EVENT_DAY.HANGUP_CAUSE.like("NO_ANSWER")
    .or(BO_SIP_CTI_EVENT_DAY.HANGUP_CAUSE.like("NO_USER_RESPONSE")))
  .fetch();

關於你對LIKE的使用的側面說明

請注意,下划線( _ )字符是SQL中的單字符通配符,因此您的LIKE謂詞可能不完全正確。 理想情況下,只需使用普通的比較謂詞,例如:

  • kierunek = 'P'
  • hangup_cause IN ('NO_ANSWER', 'NO_USER_RESPONSE')

你真的不需要LIKE

暫無
暫無

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

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