Question

"SELECT accepted AS accepted1 
 FROM friends WHERE from_id = :request_from AND to_id = :request_to 
 UNION SELECT accepted AS accepted2 
 FROM friends WHERE from_id = :request_to2 AND to_id = :request_from2"

in this query i am getting all results as accepted1 even if the second part (after UNION SELECT) of the query was true. How do i get the result as a accepted2 from second part of the query?

Was it helpful?

Solution

This is how the UNION statement behaves. Very generally speaking, it combines the results of two queries into one. So since you're only selecting a single field in each query, there is only a single column -- a single column can only have a single name.

If you need to know which query it came from, you could add a second column and use it to know.

SELECT accepted, 'accepted1' as source
FROM friends 
WHERE from_id = :request_from 
    AND to_id = :request_to 
UNION 
SELECT accepted, 'accepted2'  
FROM friends 
WHERE from_id = :request_to2 
    AND to_id = :request_from2

OTHER TIPS

I think you could simplify the query by doing this:

SELECT accepted, from_id AS 'from' FROM friends 
WHERE (from_id = :request_from AND to_id = :request_to) 
   OR (from_id = :request_to2  AND to_id = :request_from2)

The second field from indicates which of the parts has been used

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top