简体   繁体   English

要检索的列数据完全匹配

[英]Exact match of column data to be retrieved

I have scenario where i need to retrieve record only when two columns from two different tables needs to exactly match 我有一种情况,仅当来自两个不同表的两列需要完全匹配时才需要检索记录

Table A
--------
Column1 Column2
Item1    Code1
Item1    Code2
Item1    Code3
Item1    Code4

Table B
-------

Column1 Column2 Column3
Item2   Code1    10
Item2   Code2    10
Item2   Code3    10
Item2   Code4    10

Item3   Code1    10
Item3   Code2    10
Item3   Code3    10    

Now I need to get Column 3 from Table B only when All the Values in Column2 in both tables matches. 现在,仅当两个表中Column2中的所有值都匹配时,才需要从表B中获取列3。 item 3 should be ignored since not all the values of column2 in table B matches table A column 2 第3项应忽略,因为并非表B中column2的所有值都与表A列2匹配

End Result I am expecting is 我期望的最终结果是

Column1 Column2 Column3
Item1   Code1    10
Item1   Code2    10
Item1   Code3    10
Item1   Code4    10

Suggestion pls for this SQL. 有关此SQL的建议。

try an inner join with a subquery.. the having clause is key here to make sure that it matches all 4 conditions. 尝试使用子查询进行内部联接。.hading子句在这里很关键,以确保它匹配所有4个条件。

Query 询问

SELECT a.*, b.column3 
FROM tablea a
JOIN tableb b on b.column2 = a.column2
WHERE b.column1 IN
(   SELECT b.column1
    FROM tableB b
    WHERE b.column2 in(select column2 from tablea)
    GROUP BY b.column1
    HAVING COUNT(*) = 4
);

DEMO DEMO

OUTPUT OUTPUT

Column1 Column2 Column3
Item1   Code1   10
Item1   Code2   10
Item1   Code3   10
Item1   Code4   10

NOTE: 注意:

if you dont actually know the number of codes for a particular item you can also make it dynamic like this. 如果您实际上不知道特定项目的代码数量,也可以像这样使它动态化。

SELECT a.*, b.column3 
FROM tablea a
JOIN tableb b on b.column2 = a.column2
WHERE b.column1 IN
(   SELECT b.column1
    FROM tableB b
    WHERE b.column2 in(select column2 from tablea)
    GROUP BY b.column1
    HAVING COUNT(*) = (SELECT count(*) from tablea where column1 = 'Item1')
);

all you need to know is the product you want to match.. aka which item 您只需要知道要匹配的产品即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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