简体   繁体   中英

Better solution for Inserting Data from multipe tables, T-sql

I have three tables - MainTable , Country and VisaType .

Table 1 - MainTable :

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

Table 2 - Country :

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

Table 3 - VisaType

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

I want to get the following result:

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

I am doing this so:

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'

The question is : what should be better solutions for this task and is it possible to make it with using inner joins?

Your query is fine. And, as much as I admonish against using commas, you actually are doing a Cartesian product here. I would phrase this as:

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

Some people do expression this as a 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';

All three are equivalent, but I would discourage using the version with the comma.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM