What you are looking for is the SQL
DISTINCT
keyword which returns only distinct (different) values.
Also your SQL command is much too complicated (contains redundant information). As far as I understand, you want to query the single table 'union' for a single field. Then the general syntax might be
SELECT DISTINCT exercise_id_fk FROM union WHERE tag_id_fk IN (<list_of_tags>)
The above uses also the SQL
IN
keyword to match values from a list.
Untested example from scratch:
$tags_array = $_SESSION['tags_array'];
$tags = count($tags_array);
$sql = "SELECT DISTINCT exercise_id_fk FROM 'union' WHERE tag_id_fk";
if ($tags == 1) {
$sql .= "=" . $tags_array[0];
}
else {
$sql .= " IN (" . $tags_array[0];
for ($i = 1; $i < $tags; $i++) {
$sql .= ", " . $tags_array[$i];
}
$sql .= ")"
}
Note that I have quoted the table name 'union' because it is a reserved SQL word.