从两个sql表中获取行

时间:2011-09-18 04:58:53

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

我有两张表RecordMasterDummy

两者都有Mobile_NumberInsert_Date

等列

我想要像

这样的行

1)来自Dummy表我想获取Mobile_NumberInsert_DateRecordMaster相比的行。

2)来自Dummy表我想获取那些与Mobile_Number相比Insert_DateRecordMaster不同的行。

之后在1)条件中我想只获取那些Cpv_Status不为空的行。 (CPV_STATUS)Dummy表中的一列..

请帮帮我........

2 个答案:

答案 0 :(得分:1)

  1. 满足您的1)和3)需求(可选择包括WHERE)。
  2. SELECT d.* 
    FROM Dummy d 
    INNER JOIN RecordMaster r 
       ON r.mobile_number = d.mobile_number
       AND r.insert_date = d.insert_date
    WHERE d.Cpv_Status IS NOT NULL 
    

    2

    SELECT d.* 
    FROM Dummy d
    WHERE NOT EXISTS 
        (SELECT 1 
         FROM RecordMaster r 
         WHERE r.mobile_number = d.mobile_number
         AND r.insert_date = d.insert_date
        )
    

    要插入这些:

    INSERT INTO RecordMaster(mobile_number, insert_date)
      SELECT d.mobile_number, insert_date 
      FROM Dummy d
      WHERE NOT EXISTS 
        (SELECT 1 
         FROM RecordMaster r 
         WHERE r.mobile_number = d.mobile_number
         AND r.insert_date = d.insert_date
        )
    

答案 1 :(得分:0)

以下查询将为您提供虚拟中与RecordMaster

中的记录匹配的所有记录
SELECT a.Mobile_Number,a.Insert_Date ,a.Cpv_Status
FROM RecordMaster a, Dummy b
WHERE a.Mobile_Number = b.Mobile_Number and a.Insert_Date = b.Insert_Date

以下查询将为您提供Dummy中RecordMadter

中没有匹配记录的记录
SELECT a.Mobile_Number,a.Insert_Date ,a.Cpv_Status
FROM Dummy a
WHERE STR(a.Mobile_Number)+STR(a.Mobile_Number) not in 
(SELECT STR(Mobile_Number)+STR(Insert_Date) FROM RecordMaster)

如果你需要将这两个结果合并到一个结果集中,那么就像这样使用UNION

SELECT a.Mobile_Number,a.Insert_Date ,a.Cpv_Status
FROM RecordMaster a, Dummy b
WHERE a.Mobile_Number = b.Mobile_Number and a.Insert_Date = b.Insert_Date

UNION

SELECT a.Mobile_Number,a.Insert_Date ,a.Cpv_Status
FROM Dummy a
WHERE STR(a.Mobile_Number)+STR(a.Mobile_Number) not in 
(SELECT STR(Mobile_Number)+STR(Insert_Date) FROM RecordMaster)

最后,您可以将所需的任何过滤器应用于最终结果集,如下所示:

select * from (

SELECT a.Mobile_Number,a.Insert_Date , a.Cpv_Status,a.Cpv_Status
FROM RecordMaster a, Dummy b
WHERE a.Mobile_Number = b.Mobile_Number and a.Insert_Date = b.Insert_Date

UNION

SELECT a.Mobile_Number,a.Insert_Date ,a.Cpv_Status
FROM Dummy a
WHERE STR(a.Mobile_Number)+STR(a.Mobile_Number) not in 
(SELECT STR(Mobile_Number)+STR(Insert_Date) FROM RecordMaster)

) where Cpv_Status is not null