Campbell Wray Campbell Wray - 1 month ago 5
SQL Question

SQL UNION - Is it possible to use a result from first SELECT in the second SELECT

I am connecting to an SQL server with multiple tables,

As an example lets assume there are 2 tables:

  1. a table (names) linking ids to products names e.g.
    5, apple

  2. a table (prices) linking product names to prices e.g.
    apple, $4
    eggs, $5
    oranges, $12

I would like to write a
command that can link this data together, something along the lines of:

SELECT id, name
FROM names
SELECT price
FROM prices where name = **name from the first bit**

The returned result would be something like:

5, apple, $4
12, eggs, $5

Oranges wouldn't be returned as it wasn't in the names table.

For a bit of background: My initial plan was to first get the names then iterate through them making a new query for every name to get the price.

However this is going to be implemented with C# and Visual Studio won't allow a second query to be opened if there is currently on on the same connection

Changing to an approach similar to what I outlined above seems like a better way to achieve what I want (less queries, tidier, etc.) but other suggestions are welcome


This is a JOIN, not a UNION

SELECT,, p1.price
FROM names n1
INNER JOIN prices p1
ON =