【问题标题】:Better solution for Inserting Data from multipe tables, T-sql从多个表插入数据的更好解决方案,Tsql
【发布时间】:2018-02-10 18:37:53
【问题描述】:

我有三张桌子 - MainTableCountryVisaType

表 1 - 主表

---------------------------------------------------------------
| MainTableID | ApplicantName | CountryID | VisaTypeID | Date |
---------------------------------------------------------------

表 2 - 国家

-----------------------
| CountryID | Country |
-----------------------
|     1     |  Japan  |
|     2     | Georgia |
-----------------------  

表 3 - 签证类型

-------------------------
| VisaTypeID | VisaType |
-------------------------
|     1      |    B2    |
|     2      |   H1-B   |
------------------------- 

我想得到以下结果:

-------------------------------------------------------------------------
| MainTableID | ApplicantName | CountryID | VisaTypeID |      Date      |
-------------------------------------------------------------------------
|      1      |     George    |     2     |     1      | 2018 - 02 - 22 |
-------------------------------------------------------------------------

我正在这样做:

INSERT INTO MAINTABLE (ApplicantName, CountryID, VisaTypeID, Date)
    SELECT 'George', CountryID, VisaTypeID, '2018-02-22'
    FROM Country, VisaType    
    WHERE Country.Country = 'Georgia'  
      AND VisaType.VisaType = 'B2'

问题是:对于这项任务应该有什么更好的解决方案,是否可以使用内部连接来实现?

【问题讨论】:

    标签: sql sql-server sql-insert


    【解决方案1】:

    您的查询很好。而且,尽管我告诫不要使用逗号,但实际上你在这里做的是笛卡尔积。我将其表述为:

    INSERT INTO MAINTABLE (ApplicantName, CountryID, VisaTypeID, Date)
        SELECT 'George',c. CountryID, v.VisaTypeID, '2018-02-22'
        FROM Country c CROSS JOIN
             VisaType vt
        WHERE c.Country = 'Georgia' AND vt.VisaType = 'B2';
    

    有些人将其表达为JOIN

    INSERT INTO MAINTABLE (ApplicantName, CountryID, VisaTypeID, Date)
        SELECT 'George',c. CountryID, v.VisaTypeID, '2018-02-22'
        FROM Country c CROSS JOIN
             VisaType vt
             ON c.Country = 'Georgia' AND vt.VisaType = 'B2';
    

    这三个都是等价的,但我不鼓励使用带逗号的版本。

    【讨论】:

    • @Beginner:如果你觉得这个答案帮助你解决了你的问题,那么请accept this answer。这将表达您对花费自己的时间帮助您的人们的感激之情。
    猜你喜欢
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    相关资源
    最近更新 更多