I am connecting to an SQL server with multiple tables,
As an example lets assume there are 2 tables:
5, apple
, 12,eggs
apple, $4
, eggs, $5
, oranges, $12
I would like to write a select
command that can link this data together, something along the lines of:
SELECT id, name
FROM names
UNION
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 n1.id, n1.name, p1.price
FROM names n1
INNER JOIN prices p1
ON n1.name = p1.name
UNION combines the results of two or more queries into a single result set that includes all the rows that belong to all queries in the union. And you need INNER JOIN to combine records from two (or more) tables:
SELECT n.id,
n.name,
p.price
FROM names n
INNER JOIN prices p
ON n.name = p.name --or id
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.