Data order by which table its in SQL
So this is a weird one.
I have a search for a person that exists in the table "profile" and we have people that are allowed to become like a fan of a person. They can favorite them.
[Profile]
[uid, first, last, location][Favorite]
[A][B]The profile table consists of some basic information (more than that but thats all that needs to be displayed) and the favorite table consists of 2 unique ids. A has B as a favorite. (A -> B). From the select results i want to display different messages (like this is your friend grou开发者_如何转开发p, this is the other results).
SELECT P.firstname, P.lastname, P.location, P.uid, 2 AS type
FROM profile AS P
JOIN favorites AS F
ON F.A = 'myid' and F.B = P.uid
WHERE (P.firstname LIKE 'mich%' or P.lastname LIKE 'mich%')
So this first one gets all of the people that i consider my favorite. Second, how do i get a general result and append it to SUCH THAT there are no duplicate results?
I tried something like this.
SELECT P.firstname, P.lastname, P.location, P.uid, 2 AS fan
FROM profile AS P
JOIN favorites AS F
ON F.A = P.uid and F.B = 'myid'
WHERE (P.firstname LIKE 'micha%' or P.lastname LIKE 'micha%')
UNION
SELECT P.firstname, P.lastname, P.location, P.uid, 1 AS fan
FROM profile AS P
JOIN favorites AS F
ON F.A != P.uid and F.B = 'myid'
WHERE (P.firstname LIKE 'micha%' or P.lastname LIKE 'micha%')
I think you can combine that into one simple query using a case statement and a left join:
select p.firstname, p.lastname,
p.location, p.uid,
case when f.A is null then 1
else 2
end as type
from profile as p
left join favorites as f
on p.uid = f.B and f.A = 'myid'
where p.firstname like 'mich%' or p.lastname like 'mich%'
This will search profiles for your WHERE clause, and if it matches your favorites join the type field will evaluate to a 2, otherwise it will be one.
I believe this is what you want...
SELECT P.firstname, P.lastname, P.location, P.uid, CASE F.A = P.uid THEN 2 ELSE 1 END AS fan
FROM profile AS P
LEFT JOIN favorites AS F
ON F.B = P.uid
WHERE (P.firstname LIKE 'micha%' or P.lastname LIKE 'micha%')
精彩评论