I know how to select a field from subquery:
SELECT
ID, fck, f1,
(SELECT f2 FROM tbl2 Y WHERE Y.ID = T.fck) AS f2
FROM
tbl1 T
If I need to select two columns from the subquery, actually I do:
SELECT
ID, fck, f1,
(SELECT f2 FROM tbl2 Y WHERE Y.ID = T.fck) AS f2,
(SELECT f3 FROM tbl2 Y WHERE Y.ID = T.fck) AS f3
FROM
tbl1 T
There is a way to avoid two subqueries? Something like:
SELECT
ID, fck, f1,
(SELECT f2, f3 FROM tbl2 Y WHERE Y.ID = T.fck) AS f2, f3
FROM
tbl1 T
Database is SQL Server 2008 R2.
I know this simple example may be rewritten using JOINs, but there are real cases where there aren't equivalent forms using JOIN.
If you want compare two or more columns. you must write a compound WHERE clause using logical operators Multiple-column subqueries enable you to combine duplicate WHERE conditions into a single WHERE clause.
You can write subqueries that return multiple columns. The following example retrieves the order amount with the lowest price, group by agent code.
To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.
When we have to select multiple columns along with some condition, we put a WHERE clause and write our condition inside that clause. It is not mandatory to choose the WHERE clause there can be multiple options to put conditions depending on the query asked but most conditions are satisfied with the WHERE clause.
You can use OUTER APPLY
:
SELECT t1.ID, t1.fck, t1.f1, t3.f2, t3.f3
FROM tbl1 AS t1
OUTER APPLY (
SELECT f2, f3
FROM tbl2 AS t2
WHERE t2.ID = t1.fck) AS t3
The SELECT
clause contains scalar values, so it can't handle subqueries returning more than field, or multiple records of one field.
A correlated subquery is used to get a single value, but you can simply turn your subquery into a join to do what you need:
SELECT T.ID, T.fck, T.f1, Y.f2, Y.f3
FROM tbl1 T
INNER JOIN tbl2 Y ON Y.ID = T.fck
As with any join, you also need to determine whether you need an INNER JOIN
versus OUTER JOIN
, and make sure you understand whether the relationship between tables is 1..1, 1..N, etc., but in general this is how to get multiple fields from a related table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With