我正在PostgreSQL中的两个表之间进行连接,一个在incidentnumber(opentickets)上有一个主键约束,而另一个表没有约束,并且可能有重复的incidentnumbers(incommingtickets)。尝试过滤掉重复项时出现问题。查询,
SELECT incommingtickets.*
FROM incommingtickets
LEFT JOIN opentickets
ON incommingtickets.incidentnumber = opentickets.incidentnumber
WHERE opentickets.incidentnumber IS NULL
AND incommingtickets.status NOT IN ('Closed','Cancelled', '')
一直工作,直到它碰到重复,我得到违反主键消息。如果我添加一个像<,p>这样的独特子句
SELECT DISTINCT ON (incommingtickets.incidentnumber) incommingtickets.*
FROM incommingtickets
LEFT JOIN opentickets
ON incommingtickets.incidentnumber = opentickets.incidentnumber
WHERE opentickets.incidentnumber IS NULL
AND incommingtickets.status NOT IN ('Closed','Cancelled', '')
我收到错误,
pg_query():查询失败:错误:缺少表的FROM子句条目 &#34; incommingtickets&#34;第30行:哪里有opentickets.incidentnumber = incommingtickets.incident ...
答案 0 :(得分:0)
使用WHERE子句过滤掉你不想要的副本,尽管我不清楚为什么你想加入一个&#39;指标&#39;比如门票数量。
SELECT incommingtickets.*
FROM incommingtickets
WHERE incommingtickets.incidentnumber not in (
select
distinct
incidentnumber
FROM opentickets)
AND incommingtickets.status NOT IN ('Closed','Cancelled', '')
通过这种方式,您可以在两个表之间输出重复文件。
如果您想要检查或更新opentickets
表中任何故障单的故障单状态,请尝试从incommingtickets
获取最大状态,如下所示:
WITH ticket_rows AS(
SELECT
rank() OVER (PARTITION BY ticket_id ORDER BY ticket_timestamp desc) as row_number,
ticket_id,
ticket_status,
ticket_timestamp
from incommingtickets
)
SELECT incommingtickets.*, opentickets_2.*
FROM opentickets o
LEFT JOIN ticket_rows ON ticket_rows.ticket_id= opentickets.ticket_id AND ticket_rows.row__number=1
如果这些不是你的目标,那么请你更好地解释你想要通过左连接实现的目标。