Thank to your help I made a view in my database called ‘people’ that retrieve data using three functions called ‘isUserVerified‘, ‘hasUserPicture‘ and ‘userHobbies‘ from two tables called ‘users’ and ‘user_hobbies‘:
SELECT
`u`.`id` AS `id`,
`isUserVerified`(`u`.`id`) AS `verification`,
`hasUserPicture`(`u`.id) AS `profile_picture`,
`userHobbies`(`h`.`user_id`) AS `hobbies`
FROM
`people`.`users` u
INNER JOIN
`people`.`user_hobbies` h
ON
`h`.`user_id` = `u`.`id`
It returns the following output:
I realise that this is because I am joining on:
`h`.`user_id` = `u`.`id`
But it is not what I want. For each user I want to run the tree function and return if they are verified, have a profile picture and a hobby. I am expecting 10 users with the relative information. Can you help? Thank you
2
Answers
You can replace
INNER JOIN
withLEFT JOIN
to see all of the users, sinceusers
table is stated on the left of theJOIN
keyword, andINNER
looksup for the exact match in the condition. e.g. if there’s no spesific user id inserted into the hobbies table, the related row is not returned byINNER JOIN
.I don’t think you need to join to
hobbies
at all. Your functions are doing the work for you:Note that user-defined functions tend to slow queries down, sometimes a lot. Functions may be a good idea in some languages, but in SQL it is better to express the logic as
JOIN
s andGROUP BY
s.Also, there is no reason to use backticks if the identifiers don’t have “bad” characters. Unnecessary backticks just make the query harder to write and read.