简体   繁体   中英

Is there any way to use multiple source tables in FROM clause without using JOIN in SQL Server?

I can implement one nested SELECT statement in the FROM clause like this and it works:

SELECT [table1].[ID] as [table_1_ID]
FROM
(SELECT [ID] FROM  [the_table_1] WHERE [address] like 'street5' ) as [table1]

Ideally, I wish to add multiple similar nested SELECT statement inside the FROM clause without using join, to end up something like this (the following code obviously doesn't work)

 SELECT [nested_selects].[table1].[ID]  as [table_1_ID],
        [nested_selects].[table2].[ID]  as [table_2_ID]
    FROM (
    (SELECT [ID] FROM  [the_table_1] WHERE [address] like 'street5' ) as [table1],
    (SELECT [ID] FROM  [the_table_2] WHERE [address] like 'street5' ) as [table2]
    ) as [nested_selects]

(From each source table I need only one single value. WHERE clause does that.)

I know how to do it with JOIN, but for some reason I wish to do it without JOIN. Is such a thing possible in SQL Server?

If you can guarantee that only a single value will be returned from the subqueries, you can nest the selects inside the select. You don't need a from at all (I have replaced your like with = ):

select
   table_1_id = (SELECT [ID] FROM  [the_table_1] WHERE [address] = 'street5' ),
   table_2_id = (SELECT [ID] FROM  [the_table_2] WHERE [address] = 'street5' );

You don't technically have to enforce this guarantee. But if you happen to get more than one row back for a subquery in the select, SQL with throw a Subquery returned more than 1 value error. So, either put a unique constraint on address , or add something to each sub-select that guarantees only one row is returned.

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