内部加入Sql查询

时间:2017-05-19 04:25:03

标签: sql oracle join union

我有一个有3个表的问题:

1.Review(作业ID)

2.Job(BusinessNumber)

3.Business(BusinessNumber)(外键)。

我需要检索数据并创建包含4列HighestBusinessHighestRatingLowestBusinessLowest Rating的表格。

select business.businessname AS HIGHESTRATEDBUSINESS, 
        max(review.reviewrating) as HIGHEST
from business 
    inner join job 
        on job.selectedbusinessabnnumber=business.abnnumber 
    inner join review 
        on review.jobid=job.jobid 
where review.reviewrating = (select max(reviewrating)
                             from review)  
GROUP BY businessname 
UNION 
select business.businessname AS LOWESTRATEDBUSINESS, 
     MIN(review.reviewrating) as HIGHEST
from business 
    inner join job 
        on job.selectedbusinessabnnumber=business.abnnumber 
    inner join review 
         on review.jobid=job.jobid 
where review.reviewrating = (select MIN(reviewrating)
                               from review)
GROUP BY businessname
/

我现在没有创建表格,我只想要显示四列。

1 个答案:

答案 0 :(得分:0)

UNION运算符从具有相同投影的两个集合生成一个结果集。您需要的是四列的新投影。因此,将两个子查询转换为内联视图并使用CROSS JOIN:

select h.highestratedbusiness
       , h.highest
       , l.lowestratedbusiness
       , l.lowest
from
    (select business.businessname AS HIGHESTRATEDBUSINESS, 
            max(review.reviewrating) as HIGHEST
    from business 
        inner join job 
            on job.selectedbusinessabnnumber=business.abnnumber 
        inner join review 
            on review.jobid=job.jobid 
    where review.reviewrating = (select max(reviewrating)
                                from review)  
    GROUP BY businessname ) h
cross join 
        (select business.businessname AS LOWESTRATEDBUSINESS, 
             MIN(review.reviewrating) as HIGHEST
        from business 
            inner join job 
                on job.selectedbusinessabnnumber=business.abnnumber 
            inner join review 
                 on review.jobid=job.jobid 
        where review.reviewrating = (select MIN(reviewrating)
                                       from review)
        GROUP BY businessname ) l
/

CROSS JOIN为连接集中的每个记录组合生成一条记录。当数据产生一个评级最高的业务和一个评级最低的业务时,这将是正常的。但如果在其中一个或两个地方都存在平局,它将生成笛卡尔积。有很多方法可以解决这个问题,如果这对你来说是个障碍,请改进你的问题。