QUERY 1
WITH CUST1 AS
(SELECT CUSTOMER_ID, TYPE FROM CUSTOMERS WHERE CONDITION),
CARS1 AS
(SELECT * FROM CARS INNER JOIN CUST1 ON
CUST1.CUSTOMER_ID = CARS.CUSTOMER_ID AND
CUST1.TYPE = CARS.TYPE) select * from CARS1;
CUSTOMERE TABLE
CUSTOMER_ID || TYPE
------------|| -------
1 || 5
2 || 5
3 || 2
4 || 2
CARS TABLE
CAR_ID || CUSTOMER_ID || TYPE || SN || DATE
------- || ------------ || ------ || ----- || -------
1 || 1 || 5 || 0123 || 02/06/1999
2 || 1 || 2 || 2365 || 03/08/1999
3 || 1 || 3 || 5156 || 03/02/1999
4 || 3 || 1 || 8651 || 03/03/1999
5 || 2 || 5 || 2555 || 03/09/1999
6 || 2 || 2 || 8562 || 03/18/1999
QUERY 1结果
CAR_ID || CUSTOMER_ID || TYPE || SN || DATE
------- || ------------ || ------ || ----- || --------
1 || 1 || 5 || 0123 || 02/06/1999
5 || 2 || 5 || 2555 || 03/09/1999
以上查询加入临时表" CUST1"用实际表格" CARS"列CUSTOMER_ID
和TYPE
上。
现在,我希望实现的是从CARS中选择属于客户的DATE AS DATE2和SN AS SN2
对于CUSTOMER_ID,CARS.TYPE = 2来自JOIN条件。
然而,困境在于我不想重新加入/使用子查询,因为CARS表非常大。 由于其他原因,请忽略临时表方法,因为它在其余代码中使用。 当前列为CUSTOMER_ID,基于CUSTOMER_ID的其他两列为SN和TYPE。
预期结果
CAR_ID || CUSTOMER_ID || TYPE || SN || DATE || DATE2 || SN2
------- || ------------ || ------ || ----- || -------- || ------- || -----
1 || 1 || 5 || 0123 || 02/06/1999 || 03/08/1999 || 2365
5 || 2 || 5 || 2555 || 03/09/1999 || 03/18/1999 || 8562
答案 0 :(得分:0)
我认为条件聚合会做你想要的。我不确定实际的逻辑是什么,但它似乎是沿着这些方向:
SELECT CAR_ID, CUSTOMER_ID, 5 as TYPE,
MAX(CASE WHEN TYPE = 5 THEN SN END) as SN,
MAX(CASE WHEN TYPE = 5 THEN DATE END) as DATE,
MAX(CASE WHEN TYPE = 2 THEN SN END) as SN2,
MAX(CASE WHEN TYPE = 2 THEN DATE END) as DATE2,
CARS c INNER JOIN CUST1 cu
ON cu.CUSTOMER_ID = c.CUSTOMER_ID AND
cu.TYPE = c.TYPE
WHERE CONDITION
GROUP BY CAR_ID, CUSTOMER_ID;
答案 1 :(得分:0)
我不确定你可以不加入汽车。你的汽车桌有多大?使用我的简单测试,我发现我正在创建一个布隆过滤器,它可能足以使查询执行。为什么不尝试看看你是否真的有问题?也许发布执行计划。例如:
select c.car_id, c.customer_id, c.type, c.sn, c.car_date, c2.sn, c2.car_date, c2.sn
from cars c
join cust cu
on c.customer_id = cu.customer_id
and c.type = cu.type
join cars c2
on c2.customer_id = cu.customer_id
where c2.type = 2
给出
CAR_ID CUSTOMER_ID TYPE SN CAR_DATE SN CAR_DATE SN
---------- ----------- ---------- ---- --------- ---- --------- ----
1 1 5 0123 06-FEB-99 2365 08-MAR-99 2365
5 2 5 2555 09-MAR-99 8652 18-MAR-99 8652
select * from table( dbms_xplan.display_cursor( null, null, 'TYPICAL' ) );
----------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes |
----------------------------------------------------------------
| 0 | SELECT STATEMENT | | | |
|* 1 | HASH JOIN | | 2 | 234 |
| 2 | JOIN FILTER CREATE | :BF0000 | 2 | 130 |
|* 3 | HASH JOIN | | 2 | 130 |
|* 4 | TABLE ACCESS STORAGE FULL| CARS | 2 | 78 |
| 5 | TABLE ACCESS STORAGE FULL| CUST | 4 | 104 |
| 6 | JOIN FILTER USE | :BF0000 | 6 | 312 |
|* 7 | TABLE ACCESS STORAGE FULL | CARS | 6 | 312 |
----------------------------------------------------------------