内部加入SQL表

时间:2017-01-09 13:33:49

标签: sql sql-server join

我收到了以下TICKET表:

DELIVERY_CODE,
TICKET_ID,
TIME_SMTP

投放代码有5 values (100001,100002,100003,100004,100005)

我想知道哪些ticket_id尚未与DELIVERY_CODE 100002一起提供但之前已DELIVERY_CODE 1000001。所有ticket_id都已通过DELIVERY_CODE: 100001

初始发送

所以我应该像这样在桌面上进行内部联接?

SELECT (SELECT *
FROM TICKET A
WHERE DELIVERY_CODE =  '1000001')
FROM TICKET
LEFT JOIN (SELECT *
           FROM TICKET B
           WHERE DELIVERY_CODE =  '1000002')
    ON A.TICKET_ID = B.TICKET_ID
WHERE B.TICKET_ID IS NULL`

5 个答案:

答案 0 :(得分:2)

您可以使用function my_timer(hObject, eventdata) % I think I'm supposed to pass (hObject, eventdata) to my_timer % handles should be getting the current figure from hObject handles = guidata( ancestor(hObject, 'figure1') ); timeout = getappdata(handles.figure1,'timeout'); t_left = timeout - 1.0; % show the updated time set(handles.timerBox,'String',num2str(t_left)); % update 'timeout' setappdata(handles.figure1,'timeout',t_left)

where exists

好的,重新阅读问题后,您可以反过来使用select A1.* from Ticket A1 where A1.Delivery_Code = '1000002' and exists (select 1 from Ticket A2 where A1.Ticket_ID = A2.TicketID and A2.Ticket_ID = '1000001')

not exists

答案 1 :(得分:0)

一种方法使用聚合:

select t.ticket_id
from ticket t
where sum(case when t.delivery_code = '1000001' then 1 else 0 end) > 0 and
      sum(case when t.delivery_code = '1000002' then 1 else 0 end) = 0;

sum(case)计算与每个投放代码匹配的行数。 > 0表示至少有一个; = 0表示没有。

答案 2 :(得分:0)

您可以像这样使用LEFT JOIN

SELECT DISTINCT A.*
FROM TICKET A
LEFT JOIN TICKET B 
   ON A.TICKET_ID = B.TICKET_ID AND A.TIME_SMTP < B.TIME_SMTP AND
      B.DELIVERY_CODE =  '1000002'
LEFT JOIN TICKET C
   ON A.TICKET_ID = C.TICKET_ID AND A.TIME_SMTP < C.TIME_SMTP AND
      C.DELIVERY_CODE <>  '1000002'
WHERE A.DELIVERY_CODE = '1000001' AND B.TICKET_ID IS NULL AND C.TICKET_ID IS NOT NULL

B用于检查是否存在DELIVERY_CODE = '1000002'的票证。 C用于检查是否存在至少一个DELIVERY_CODE <> '1000002'的故障单。

答案 3 :(得分:0)

SELECT a.DELIVERY_CODE
FROM TICKET a
     LEFT JOIN TICKET b ON a.ticket_id = b.ticket_id
                           AND b.DELIVERY_CODE = '1000002'
WHERE a.DELIVERY_CODE = '1000001'
      AND b.ticket_id IS NULL;

答案 4 :(得分:0)

首先 - 你提到了“内连接”,但是实现了“左连接”,所以不清楚你的意思(尽管如果有的话,左连接确实是你想要的)。

但是,我认为你最好使用一个子查询。类似的东西:

SELECT *
FROM TICKET A
WHERE DELIVERY_CODE = '1000001'
AND TICKET_ID NOT IN (SELECT TICKET_ID
                FROM TICKET 
                WHERE DELIVERY_CODE = '1000002'
                    AND TICKET_ID != A.TICKET_ID)

无论如何,我想指出你对你现有代码的错误:

SELECT (SELECT *
FROM TICKET A
WHERE DELIVERY_CODE =  '1000001')
FROM TICKET
LEFT JOIN (SELECT *
        FROM TICKET B
        WHERE DELIVERY_CODE =  '1000002')
    ON A.TICKET_ID = B.TICKET_ID
WHERE B.TICKET_ID IS NULL`

A和B仅存在于子要求的范围内,但不存在于它们之外,因此您不能对它们使用“on”。另外,您无法在select语句中选择。

您没有收到语法错误吗?