从多表格中插入数据的更好解决方案,T-sql

时间:2018-02-10 18:37:53

标签: sql sql-server sql-insert

我有三张牌桌 - MainTableCountryVisaType

表1 - MainTable

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

表2 - 国家/地区

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

表3 - VisaType

-------------------------
| 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'

问题是:对于此任务应该是更好的解决方案,是否可以使用内部联接来实现?

1 个答案:

答案 0 :(得分:2)

您的查询没问题。而且,尽管我劝告不要使用逗号,但实际上你在这里做笛卡尔积。我会这样说:

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';

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