Oracle
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> Oracle

Làm thế nào để biến 2 truy vấn có cột chung (A, B) và (A, C) thành chỉ một (A, B, C)?

Đầu tiên hãy tưởng tượng 2 truy vấn chỉ là bảng. Bạn sẽ làm điều này:

select a.producer, a.firstquerycolumn, b.secondquerycolumn
from table1 a
join table2 b on b.producer = a.producer

Bạn có thể thay thế từng bảng bằng một truy vấn (được gọi là chế độ xem trong dòng):

select a.Prod, a.AnimalsBought, b.AnimalsExploration
from
( select Producers.name Prod, count(Animals.idanimal) AnimalsBought
  from AnimalsBought, Animals, Producers
  where (AnimalsBought.idanimal = Animals.idanimal) 
  and (Animals.owner = Producers.nif) 
  group by Producers.name
) a
join
( select Producers.name Prod, count(Animals.idanimal) AnimalsExploration
  from AnimalsExploration, Animals, Producers
  where (AnimalsExploration.idanimal = Animals.idanimal) 
  and (Animals.owner = Producers.nif)
  group by Producers.name
) b
on a.Prod = b.Prod;

Bạn có thể cần phải thay đổi "tham gia" của tôi thành "tham gia bên ngoài đầy đủ" nếu một truy vấn có thể trả về dữ liệu cho một nhà sản xuất trong khi truy vấn kia thì không. Tôi cũng sẽ có xu hướng cấu trúc lại truy vấn như sau, tạo một truy vấn chính trên Nhà sản xuất bên ngoài được kết hợp với 2 truy vấn phụ (với Nhà sản xuất đã bị xóa):

select Producers.name Prod, a.AnimalsBought, b.AnimalsExploration
from Producers
left outer join ( select Animals.owner, count(AnimalsBought.idanimal) AnimalsBought
                    from AnimalsBought, Animals
                   where AnimalsBought.idanimal = Animals.idanimal
                   group by Animals.owner
                ) a
           on a.owner = Producers.nif
left outer join ( select Animals.owner, count(Animals.idanimal) AnimalsExploration
                    from AnimalsExploration, Animals
                   where AnimalsExploration.idanimal = Animals.idanimal
                   group by Animals.owner
                ) b
           on b.owner = Producers.nif;

(Đây là loại truy vấn mà tôi đã kiểm tra hiệu suất của bên dưới).

Thay vì làm cồng kềnh câu trả lời này với thông tin có lẽ không được OP quan tâm, ghi chú của tôi về hiệu suất tương đối của các truy vấn con vô hướng và chế độ xem nội tuyến trong Oracle (do PerformanceDBA yêu cầu) hiện đang ngoại tuyến tại đây:Ghi chú về Hiệu suất



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Oracle SQL:Cách sử dụng hơn 1000 mục bên trong mệnh đề IN

  2. Chèn vào Oracle và truy xuất ID trình tự đã tạo

  3. Tính vui nhộn của truy vấn con Oracle

  4. Thay đổi cổng Oracle từ cổng 8080

  5. SQLRecoverableException:I / O Exception:Đặt lại kết nối