SQL查询 - 选择包含不同表中数据的行

时间:2014-02-13 14:22:01

标签: sql sql-server sql-server-2008 tsql

我有2张桌子。 e.g:

table1:

|Alias1|Alias2       |Alias3|
---------------------
|qaz   | **abc**def  |wsx   |
|edc   |rfv          |tgb   |

table2:

|Alias1    |Alias2 |Alias3|
---------------------
|**abc**   | qwe   |rty   |
|zxc       |zxc    |vbn   |

我想仅显示table1alias1 table2 Alias2 table1中{{1}}所包含的{{1}}行中的行?

4 个答案:

答案 0 :(得分:2)

SELECT t1.* 
FROM table1 t1 
INNER JOIN table2 t2 on t1.Alias2=t2.alias1

答案 1 :(得分:1)

select * from table1 t1
  where exists (  select 1 from table2 t2  
                       where t2.Alias1 = t1.Alias2)

答案 2 :(得分:0)

尝试:

select *
  from table1
 where exists
 (select 'x'
          from table2
         where table1.alias2 like concat('%', table2.alias1, '%'))

答案 3 :(得分:0)

我希望以下查询有用

CREATE TABLE #Table1 (
                        Alias1 VARCHAR(35),
                        Alias2 VARCHAR(35),
                        Alias3 VARCHAR(35)
                        )
Go

CREATE TABLE #Table2 (
                        Alias1 VARCHAR(35),
                        Alias2 VARCHAR(35),
                        Alias3 VARCHAR(35)
                        )
GO
INSERT INTO #Table1(Alias1,Alias2,Alias3)
SELECT 'qaz','**abc**','wsx'
UNION ALL
SELECT 'edc','rfv','tgb'
GO
INSERT INTO #Table2(Alias1,Alias2,Alias3)
SELECT '**abc**','qwe','rty'
UNION ALL
SELECT 'zxc','zxxc','vbn'
GO
SELECT 
        t1.Alias1,
        t1.Alias2,
        t1.Alias3
FROM #Table1 t1
JOIN #Table2 t2
ON t1.Alias2 = t2.Alias1
GO
DROP TABLE #Table1
DROP TABLE #Table2