I have in database:
User:
id | name
1 | one
2 | two
3 | three
4 | four
5 | five
House:
id | name
1 | London
2 | Barcelona
UserHouse:
id_user | id_house
1 | 1
2 | 2
4 | 1
How can i use in SQL query IF and ISSET?
SELECT * from User
I would like receive:
users:
name | has_house
1 | yes
2 | yes
3 | no
4 | yes
5 | no
I must start my query with SELECT * from User. I can't star from House or UserHouse. Is possible? If yes, how?
I can use also DOCTRINE and Symfony.
Try using LEFT JOIN
SELECT a.id, IF(COALESCE(b.id_user, 1) = 1, 'no', 'yes') has_house
FROM user a
LEFT JOIN userhouse b
on a.id = b.id_user
If you realy can start your query only with SELECT * from User, you can try this:
SELECT * FROM User
JOIN (
SELECT
User.id id_user,
IF(UserHouse.id_house > 0, 'yes', 'no') AS has_house
FROM
User
LEFT JOIN
UserHouse ON UserHouse.id_user = User.id
) HasHouse ON HasHouse.id_user = User.id;
if you are using sql server, you should use instead of the if statement a case one.
SELECT user.id, 'Has House' =
CASE COALESCE(b.id_user, 0)
WHEN 0 THEN 'No'
ELSE 'Yes'
END
FROM user as u leftjoin userhouse as uh on u.id = uh.id_user
May be this will be helpful,