你怎么写这个查询?

时间:2010-09-17 18:50:47

标签: sql oracle oracle9i

我有两张桌子。 表的结构如下。

TRAILERS_INVENTORY

  • TRAILER_TYPE VARCHAR2(100)
  • TRAILER_LENGTH INT
  • TRAILER_WIDTH INT
  • YEAR_OF_MANUFACTURE INT

NEW_INVENTORY

  • NEW_INVENTORY_TYPE_ID INT,
  • TRAILER_TYPE VARCHAR2(100),
  • TRAILER_LENGTH INT,
  • TRAILER_WIDTH INT,
  • YEAR_OF_MANUFACTURE INT

我想列出所有没有NEW_INVENTORY_TYPE_ID的预告片。我正在使用Oracle 9.2。

一种方法是使用

行的集合操作
SELECT TRAILER_TYPE
 FROM TRAILERS_INVENTORY 
WHERE TRAILER_TYPE NOT IN (SELECT TRAILER_TYPE, 
                                  TRAILER_LENGTH, 
                                  TRAILER_WIDTH, 
                                  YEAR_OF_MANUFACTURE 
                             FROM TRAILERS_INVENTORY 
                           INTERSECT 
                           SELECT TRAILER_TYPE, 
                                  TRAILER_LENGTH, 
                                  TRAILER_WIDTH, 
                                  YEAR_OF_MANUFACTURE 
                             FROM NEW_INVENTORY);

还有其他方法吗?

3 个答案:

答案 0 :(得分:4)

我看到了几个选项

SELECT
    TRAILER_TYPE
FROM
    TRAILERS_INVENTORY
WHERE
    TRAILER_TYPE NOT IN (SELECT TRAILER_TYPE FROM NEW_INVENTORY)

或者:

SELECT
    TRAILER_TYPE
FROM
    TRAILERS_INVENTORY
LEFT JOIN
    NEW_INVENTORY
    ON (NEW_INVENTORY.TRAILER_TYPE = TRAILERS_INVENTORY.TRAILER_TYPE)
WHERE
    NEW_INVENTORY.NEW_INVENTORY_TYPE_ID IS NULL

答案 1 :(得分:1)

所以,问题是如何在不使用“set”操作的情况下执行此查询?

我可以问你为什么不使用套装?

你在SQ​​L中所做的一切都是基于集合,但是如果你想要一个更慢,更不优雅的解决方案,你可以将你的集合大小减少到1并使用PL / SQL循环TRAILERS_INVENTORY

declare
    v_exists varchar2(1 char);
begin
    for item in (select distinct trailer_type from trailers_inventory) loop
        begin
            select 'Y' into v_exists from new_inventory
            where trailer_type = item.trailer_type;
        exception
            when no_data_found then
                v_exists := null;
        end;
        if v_exists is null then
            dbms_output.put_line(item.trailer_type || ' not in ' || ' NEW_INVENTORY');
        end if;
    end loop;
end;
/

伊克!这就是设置操作的原因。

:)

答案 2 :(得分:0)

怎么样:

SELECT 
TRAILER_TYPE, 
TRAILER_LENGTH, 
TRAILER_WIDTH, 
YEAR_OF_MANUFACTURE 
FROM TRAILERS_INVENTORY 
MINUS
SELECT 
TRAILER_TYPE, 
TRAILER_LENGTH, 
TRAILER_WIDTH, 
YEAR_OF_MANUFACTURE 
FROM NEW_INVENTORY