question

ashcosta2 avatar image
ashcosta2 asked

How to Query from 2 tables

[link text][1] [1]: /storage/temp/3121-sql-query.xls I have a database by the name CARS with 2 tables. I need help in querying data from both these tables and get a output based on ID(100).. Any help is highly appreciated.
joinssql queryunion
sql-query.xls (19.0 KiB)
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Tom Staab avatar image
Tom Staab answered
There are 2 general methods for combining data from 2 sources. - One is done using a JOIN to match rows from the 2 sources based on one or more key values. The 2 sources can have very different columns, and the columns are combined so the total number of columns available (but not necessarily returned) in the output is the sum of the number of columns from each source. - The other method uses UNION or UNION ALL to merge the 2 sources into one. Unlike a JOIN, the 2 sources must have the same number of columns with the same data types, and the output matches those columns as well. The UNION ALL operation returns all of the data from the first source plus all of the data from the second. Without specifying ALL, the UNION operation removes duplicate rows and just returns distinct rows. You said you want to get output "based on ID", so I originally thought you wanted a JOIN. This is older documentation (for SQL Server 2008 R2), but it still applies and explains the various types of JOINs. [ https://technet.microsoft.com/en-us/library/ms191472(v=sql.105).aspx][1] When I opened your Excel worksheet, however, your output contains the the rows from Table1 plus the row from Table2. That looks more like a UNION. The first 3 links in the following article explain UNION and UNION ALL along with the similar semi-join and anti-join operators INTERSECT and EXCEPT. [ https://technet.microsoft.com/en-us/library/ms186316(v=sql.105).aspx][2] Based on your tables and output in the worksheet, I believe this is what you want: SELECT ID, GroupId, Text FROM Table1 UNION ALL SELECT ID, GroupId, Text FROM Table2 ; [1]: https://technet.microsoft.com/en-us/library/ms191472(v=sql.105).aspx [2]: https://technet.microsoft.com/en-us/library/ms186316(v=sql.105).aspx
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.