문제

"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?

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top