简体   繁体   中英

SQL server 2012 select issues

I have a database called X. In this DB I have two tables A and B. Table A have 89 rows, table b have 49. When I peform two independent SELECT's result ir correct, but when i mix and try to peform one select for both tables I'm getting back some mysterious number of rows.

For example:

SELECT * FROM A (89 rows, that's correct)
SELECT * FROM B (49 rows, that's correct)

SELECT * FROM A, B (4361 rows, and information there is repeating and duplicating)

Thanks!

I think you're actually looking for

SELECT * FROM A
UNION ALL
SELECT * FROM B

I think you want the results of both tables in one result set, and the way of doing that is to use UNION between the SELECT statements.

Mind you, this will only work if the columns in A and B are identical, in terms of datatype and in the table's definition.

The datatype of column #1 from table A will have to be the same as the datatype of column #1 from table B and so on. (this is valid only if you use SELECT * )

You can also specify the columns so the datatypes match, in order.

SELECT col1, col3, col2 from A
UNION ALL
SELECT col2, col1, col3 from B

(if col1 from A has the same datatype as col2 from B etc.)

What your last query is doing is performing CARTESIAN PRODUCT .

89 rows from TableA multiplied by 49 rows from TableB = 4361 rows in result

You are trying to select by CARTESIAN PRODUCT .

Try this

SELECT * FROM A 
UNION ALL       // It will select all 89 + 49 records from both table
SELECT * FROM B 

Or:

SELECT * FROM A 
UNION          // It will select all records from both table without duplicate
SELECT * FROM B 

The syntax you have used is the equivalent of doing a CROSS JOIN - ie it combines all rows from both tables - this returns all combinations of rows between your 2 tables - which in this case is 49 * 89.

Can you clarify what data you are expecting to return?

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