从多个表插入数据的更好解决方案,T-sql
我有三个表-从多个表插入数据的更好解决方案,T-sql,sql,sql-server,sql-insert,Sql,Sql Server,Sql Insert,我有三个表-MainTable、Country和VisaType 表1-主表: --------------------------------------------------------------- | MainTableID | ApplicantName | CountryID | VisaTypeID | Date | --------------------------------------------------------------- -----------------
MainTable
、Country
和VisaType
表1-主表:
---------------------------------------------------------------
| MainTableID | ApplicantName | CountryID | VisaTypeID | Date |
---------------------------------------------------------------
-----------------------
| CountryID | Country |
-----------------------
| 1 | Japan |
| 2 | Georgia |
-----------------------
表2-国家:
---------------------------------------------------------------
| MainTableID | ApplicantName | CountryID | VisaTypeID | Date |
---------------------------------------------------------------
-----------------------
| 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'
问题是:对于这项任务,什么应该是更好的解决方案?是否可以使用内部联接来实现它?您的查询很好。而且,正如我告诫不要使用逗号一样,这里实际上是在做笛卡尔积。我想这样说:
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';
有些人将此表达为加入:
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';
这三个都是等效的,但我不鼓励使用带有逗号的版本。@初学者:如果你觉得这个答案帮助你解决了问题,那么请。这将表达你对那些花自己的时间帮助你的人的感激之情。