Question

I'm having problems with an SQL query used to display custom profile fields and any (optional) corresponding values.

Here is the SQL query I'm using:

SELECT pf.`id`, pf.`name`, pv.`value` FROM `profile_fields` AS pf
LEFT JOIN `profile_values` AS pv ON (pf.`id` = pv.`field_id`)
WHERE (pf.`site_id` = '0' OR pf.`site_id` = '%d') AND (pv.`user_id` = '%d' OR pv.`user_id` IS NULL)
ORDER BY pf.`order` ASC

The problem I'm having is that any columns with no corresponding profile_values records are not shown at all, when they should show, but just with an empty value.

Many thanks!

Was it helpful?

Solution

Try moving the profile values conditions to the JOIN statement:

 SELECT pf.`id`, pf.`name`, pv.`value` FROM `profile_fields` AS pf
 LEFT JOIN `profile_values` AS pv ON (
         pf.`id` = pv.`field_id`  AND 
         (pv.`user_id` = '%d' OR pv.`user_id` IS NULL)
  )
 WHERE (pf.`site_id` = '0' OR pf.`site_id` = '%d')
 ORDER BY pf.`order` ASC
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top