SQL Server查询从两个具有多个条件的表中检索数据

时间:2016-08-05 06:44:58

标签: sql-server sql-server-2008

我有两个表,Table1Table2

Table1包含以下列

  • 日期
  • U_ID
  • T_ID
  • col_t1_a
  • col_t1_b
  • col_t1_c

Table2包含以下列

  • 日期
  • ux_id
  • tx_id
  • col_t2_a
  • col_t2_b
  • col_t2_c

Table1.u_id是Table2.ux_id和Table1.t_id = Table2.tx_uid的子字符串。

当以下所有条件都为真时,我试图从Table2获取所有列(col_t2_c)

  • Table1.t_id = Table2.tc_uid和
  • substring(Table2.ux_id,7,6)= Table1.u_id和
  • Table1.date = Table2.date ='yymmdd'和
  • Table1.col_t1_a ='A'和
  • Table1.col_t1_b ='B'和
  • Table1.col_t1_c ='C'

我需要一些帮助来编写SQL Server 2008查询来实现上述目标。

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:1)

尝试此查询:

SELECT * 
FROM Table2 T2
INNER JOIN
    Table1 T1 ON T1.t_id = T2.tx_uid
    AND T1.u_id = substring(t2.ux_id, 7, 6)
    AND T1.[Date] = T2.[Date]
WHERE
    T1.[date] = 'date'
    AND T1.col_t1_a = 'A'
    AND T1.col_t1_b = 'B'
    AND t1.col_t1_c = 'C'

答案 1 :(得分:0)

您的所有条件都已写好。只需将它们置于查询中:

SELECT t2.col_t2_c
FROM Table2 t2
INNER JOIN Table1 t1
    ON t1.t_id = t2.tc_uid and 
        substring(t2.ux_id,7,6) = t1.u_id and
        t1.date = t2.date
WHERE   
        t2.date = 'yymmdd' and 
        t1.col_t1_a = 'A' and
        t1.col_t1_b = 'B' and
        t1.col_t1_c = 'C'

答案 2 :(得分:0)

SELECT * 
FROM Table1 t1, Table2 t2
WHERE t1.t_id = t2.tx_uid 
AND t1.u_id = substring(t2.ux_id,7,6)
AND t1.date = t2.date
AND t2.date = 'yymmdd'
AND t1.col_t1_a = 'A'
AND t1.col_t1_b = 'B'
AND t1.col_t1_c = 'C'