内连接一列多搜索查询

时间:2016-07-15 17:00:01

标签: sql sql-server

我知道如何进行基本的内连接查询。但是由于我的数据结构,我需要从多个表中获取值以获得我需要的结果。截至目前,为了让我找到攻击记录,我必须通过此查询

SELECT * FROM OFFENSE  where TRS_IDN IN 
(SELECT TRS_IDN FROM CCH_PUBLIC.dbo.TRS where TRN_IDN IN 
(select TRN_IDN from CCH_PUBLIC.dbo.TRN where IND_IDN = 
(SELECT TOP 1 IND_IDN FROM CCH_PUBLIC.dbo.PERSON WHERE PER_IDN = @PER_IDN)))

结果如下:

OFF_IDN     TRS_IDN     AGY_TXT     DOO_DTE     AON_COD     AOL_TXT                 LDA_COD GOC_COD  ADN_COD     ADD_TXT     ADA_DTE     REF_TXT     IPN_NBR     ICA_NBR     DMV_COD

23808207    26154505    TX2270000   5/13/2013   54040014    DRIVING WHILE INTOXI    MA               205                     5/14/2013  TX227013A                1320573    

CCH_PUBLIC.dbo.TRN表格中有一个名为TRN_IDN的列。目标是将CCH_PUBLIC.dbo.OFFENSE表与CCH_PUBLIC.dbo.TRN内连接,并添加名为TRN_IDN的单列。我怎么能这样做

3 个答案:

答案 0 :(得分:1)

我不确定问题是什么,但为什么不执行以下操作来清理语法

interface MainNavigaton {

     void replaceFragment();
 }

答案 1 :(得分:0)

SELECT f1.*, f5.TRN_IDN FROM OFFENSE f1 
cross join 
(
SELECT top 1 f3.TRN_IDN FROM CCH_PUBLIC.dbo.TRS f2 inner join CCH_PUBLIC.dbo.TRN f3 on f2.TRN_IDN=f3.TRN_IDN
inner join CCH_PUBLIC.dbo.PERSON f4 on f3.IND_IDN=f4.IND_IDN
where f1.TRS_IDN =f2.TRS_IDN 
) f5

如果您想要所有链接,请减去前1

答案 2 :(得分:0)

您可以简单地将select语句与表CCH_PUBLIC.dbo.TRN一起使用,因为您的选择主要来自表CCH_PUBLIC.dbo.OFFENSE,只有像这样的where条件

SELECT  O.*, 
        TRN.TRN_IDN
FROM    OFFENSE AS O  
JOIN    CCH_PUBLIC.dbo.TRS AS TRS
ON      O.TRS_IDN = TRS.TRS_IDN
JOIN    CCH_PUBLIC.dbo.TRN AS TRN
ON      TRS.TRN_IDN = TRN.TRN_IDN

WHERE O.TRS_IDN IN 
    (SELECT TRS_IDN FROM CCH_PUBLIC.dbo.TRS WHERE TRN_IDN IN 
        (SELECT TRN_IDN FROM CCH_PUBLIC.dbo.TRN WHERE IND_IDN = 
            (SELECT TOP (1) IND_IDN FROM CCH_PUBLIC.dbo.PERSON 
                WHERE PER_IDN = @PER_IDN)))