One problem to point out before solving the problem is that each query in UNION is different and requires its own WHERE . The only condition that applies to UNION as a whole is ORDER BY . So your request requires some tweaking:
SELECT nombre FROM dbo.internados WHERE nombre = ?
Secondly, if you want both tables to have the same nombre (which is not entirely clear, but I assume it is correct), then this will not work, because it just returns a single nombre if a value is found in both tables. Probably the best way to solve this is to simply make a connection:
SELECT I.nombre FROM dbo.internados I INNER JOIN dbo.universidades U ON I.nombre = U.nombre WHERE I.nombre = ? AND U.nombre = ?
I am not 100% sure that I understand exactly what you are looking for, so please let me know if I missed the mark.
You can think of JOIN and UNION as follows:
JOIN : joins lines horizontally- Meets them on terms
- Creates new columns
- It doesnβt exactly create rows, because all the data comes from existing rows, but it will duplicate a row from one input, when the conditions correspond to several lines at another input. If both inputs have duplicates, then it multiplies the number of lines from one input by the number of matching lines with the other.
- If there is no matching condition at all (think
CROSS JOIN ), you can get a Cartesian product, which is each line in one input, consistent with each line in another. - When using
OUTER join - LEFT , RIGHT , FULL - if the rows from the internal input (or input with FULL ) do not match, NULL will be placed in columns for another input.
UNION : line stacks vertically- Usually creates new lines
- No conditions are used, no real compliance
UNION by itself (not UNION ALL ) will delete duplicate lines, even if one input has no lines
Please note that the UNION parameter can be changed to complete the task, although this is not ideal:
SELECT nombre FROM ( SELECT nombre FROM dbo.internados WHERE nombre = ? UNION ALL SELECT nombre FROM dbo.universidades WHERE nombre = ? ) N GROUP BY nombre HAVING Count(*) = 2 ;
In this way, we provide two values. Note that it is assumed that each table cannot have two identical names. If so, more work will be needed to make UNION way of doing the job.
ErikE source share