SQL查询:使用内部联接对结果行进行附加筛选

时间:2015-02-20 06:51:29

标签: mysql sql-server

鉴于Table_1:

| testing | main_val |
| AB      | VAL      |
| EF      | DIP      |

和表_2:

| main_val | for_testing |
| VAL      |             |
| VAL      | AB          |
| VAL      | CD          |
| DIP      |             |
| DIP      | GH          |

我的加入查询如下:

select table1.testing, table1.main_val, table2.for_testing from table_1 table1
inner join table_2 table2 on table1.main_val = table2.main_val

我得到以下结果:

| testing | main_val | for_testing |
| AB      | VAL      |             |
| AB      | VAL      | AB          |
| AB      | VAL      | CD          |
| EF      | DIP      |             |
| EF      | DIP      | GH          |

我的要求是获得最佳的“测试匹配”。如果testing和for_testing列匹配,那么我应该检索该行。如果没有匹配,请选择空的for_testing行。我需要结果看起来像:

| testing | main_val | for_testing |
| AB      | VAL      | AB          |
| EF      | DIP      |             |

此连接会添加更多列,这就是获得最佳匹配行的重要原因。

5 个答案:

答案 0 :(得分:0)

试试这个:

select table1.testing, table1.main_val, table2.for_testing 
from table_1 table1
inner join table_2 table2 on table1.main_val = table2.main_val 
where table1.testing =table2.for_testing 
union 
select table1.testing, table1.main_val, table2.for_testing 
from table_1 table1
inner join table_2 table2 on table1.main_val = table2.main_val 
where not in (select table1.testing, table1.main_val, table2.for_testing 
from table_1 table1
inner join table_2 table2 on table1.main_val = table2.main_val 
where table1.testing =table2.for_testing ) and t2.for_testing =""

答案 1 :(得分:0)

试试这个:

;WITH CTE AS(
    SELECT 
        t1.*,
        t2.For_Testing,
        RN = ROW_NUMBER() 
                OVER(
                    PARTITION BY t1.Main_Val 
                    ORDER BY 
                        CASE 
                            WHEN t1.Testing = t2.For_Testing THEN 1
                            WHEN t2.For_Testing = '' THEN 2
                            ELSE 999
                        END
                    )
    FROM Table_1 t1
    INNER JOIN Table_2 t2
        ON t2.MAIN_val = t1.Main_Val
)
SELECT
    Testing,
    Main_val,
    For_Testing
FROM CTE
WHERE RN = 1
ORDER BY Testing

答案 2 :(得分:0)

你必须使用左连接,并在加入时添加for_testing。

答案 3 :(得分:0)

试试这个......

这对我有用

select Table_1.testing,Table_1.main_val,Table_2.for_testing from Table_2 right join

 Table_1 on Table_2.main_val=Table_1.main_val and Table_2.for_testing=Table_1.testing

答案 4 :(得分:0)

试试这个: -

SELECT table1.testing, table1.main_val, table2.for_testing 
FROM table_1 table1 INNER JOIN table_2 table2 
ON table1.main_val = table2.main_val
WHERE table1.testing = table2.for_testing
OR table1.testing IS NULL;

我认为这可以帮助你。