简体   繁体   中英

I need to join two tables with where condition without a common column

product table                    company table                     discount table

pid  pname cost comp_id          comp_id    comp_name              dis_id     dis_name  dis_amt
    1     xxx   ##   c1                c1         click              d1       diwali     15%
    2     tv    ##   c1                c2         nick               d2        newyear    5%
    3     tv2   ##   c1                                              d3       christmas    10
    4     mob   ##   c2
    5     cam   ##   c1

I need to fetch details about companies decided to give diwali discount for its tv products and its name and discount percentage, help me to solve this....

As there is no info about companies decision to apply discount or not all you can do is to assume that discounts table data is applicable to all companies and products. The query could be like here:

Select Distinct
    c.COMP_ID, c.COMP_NAME, 'TVs' "PRODUCTS",
    d.DIS_NAME, d.DIS_AMT
From
    companies c
Inner Join 
    products p ON(p.COMP_ID = c.COMP_ID)
Inner Join 
    discounts d ON(1=1)
Where
    Upper(p.PNAME) Like('%TV%') And
    d.DIS_NAME = 'diwali'

... which for your sample data...

WITH 
    products (PID, PNAME, COST, COMP_ID) AS
        (
            Select 1, 'xxx', 100, 'c1' From Dual Union All
            Select 2, 'tv',  200, 'c1' From Dual Union All
            Select 3, 'tv2', 220, 'c1' From Dual Union All
            Select 4, 'mob', 300, 'c2' From Dual Union All
            Select 5, 'cam', 400, 'c1' From Dual 
        ),
    companies (COMP_ID, COMP_NAME) AS
        (
            Select 'c1', 'click' From Dual Union All
            Select 'c2', 'nick'  From Dual
        ),
    discounts (DIS_ID, DIS_NAME, DIS_AMT) AS
        (
            Select 'd1', 'diwali',    '15%' From Dual Union All
            Select 'd2', 'newyear',    '5%' From Dual Union All
            Select 'd3', 'christmas', '10' From Dual 
        )

... results like below.

COMP_ID COMP_NAME PRODUCTS DIS_NAME DIS_AMT
c1 click TVs diwali 15%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM