簡體   English   中英

Postgresql 兩個表之間的查詢返回一個 Id 的多個條目

[英]Postgresql query between two tables returns multiple entries for one Id

我正在嘗試進行查詢,將客戶端表上的客戶端名稱鏈接到具有相應 ID 的貨物。 我正在做這個查詢:

SELECT c.id, c.status, c.client_id, c.dt, c.cargo_date, c.cargo_hour, c.origin, c.destination, c.code_name, c.download_at, c.download_hour, c.weight, c.ramp_id, c.truck_id, c.driver_id, c.cargo_return, c.returning, c.description, cl.name, cl.id 
from cargos c, 
     clients cl 
where c.status = 'planner' and (c.destination != 'SANTIAGO') 
  or  (c.destination = 'SANTIAGO' and c.returning is not NULL) 
 AND  c.client_id = cl.id 
order by COALESCE(c.returning, c.id);

但是當我這樣做時,它會向我的客戶表中的每個客戶返回每件貨物,不是 AND c.client_id = cl.id 應該使每個 id 的結果唯一嗎?

看起來您可能在您的一個 AND 語句周圍缺少括號,以包含一個 OR 和所有其他語句:

因此,您在我添加的括號中執行 status AND 一個或另一個,並且 Client_id = cl.ID

當你在 where 子句中使用 AND 和 OR 時,你必須確保在你想要的組周圍加上大括號,否則它真的會打亂你的邏輯。

where 
c.status = 'planner' 
and 
    -- I added the opening and closing bradckets around the OR statement
    (
        (c.destination != 'SANTIAGO') 
        or (c.destination = 'SANTIAGO' and c.returning is not NULL) 
    )
AND c.client_id = cl.id

暫無
暫無

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

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