I currently have this query running on my website,
public function searchCandidates($type=null, $gender=null, $age=null)
{
//die(var_dump($age));
if($age != false) {
$age = implode(", %", $age);
}
$sql = 'SELECT `candidates`.`candidate_id`,
`candidates`.`first_name`,
`candidates`.`surname`,
`candidates`.`gender`,
`candidates`.`DOB`,
`candidates`.`talent`,
`candidates`.`availability`,
`candidates`.`youtube_showreel_1`,
`candidates`.`youtube_showreel_desc_1`,
`candidates`.`date_created`,
`candidates`.`new_talent`,
DATE_FORMAT(NOW(), "%Y") - DATE_FORMAT(`candidates`.`DOB`, "%Y") - (DATE_FORMAT(NOW(), "00-%m-%d") < DATE_FORMAT(`candidates`.`DOB`, "00-%m-%d")) as `age`,
`candidate_assets`.`url`,
`candidate_assets`.`asset_size`,
`candidate_assets`.`weight`
FROM `candidates`
LEFT JOIN `candidate_assets` ON `candidate_assets`.`candidates_candidate_id` = `candidates`.`candidate_id`
WHERE `candidates`.`show_on_site` = "urban talent" AND `candidates`.`visible` = "yes" AND `candidate_assets`.`weight` = 1';
//is there a certain criteria
if($type != "0") { $sql .= ' AND `candidates`.`talent` LIKE "%'.$type.'%"'; }
if($age != false) { $sql .= ' AND `candidates`.`playing_age` LIKE "%'.$age.'%"';}
if($gender != false){ $sql .= ' AND `candidates`.`gender` = "'.$gender.'"'; }
$sql .= ' GROUP BY `candidates`.`candidate_id` ORDER BY `candidates`.`surname` ASC, `candidate_assets`.`weight` ASC';
$query = $this->db->query($sql);
//die(print_r($query->result_array()));
//echo $this->db->last_query();
//die();
return $query->result_array();
}
I am struggling to get this query working as I wish, I want to show all results regardless of whether or not the user has a image (candidate_assets.url), however if they do have an image then I only need to show the an image that has weight of 1. At the moment, my query only brings back users that have an image that is weighted as 1.
What I want is being back all users, and if they have an image (or multiple images) then return the image that has a weight of 1.
What I am doing wrong?
Your LEFT JOIN makes no difference if you use columns from the second table in your where clause. Either allow them to be NULL in the where clause, or move them to the ON clause:
You have:
Make that:
Or possibly (less “logical”)
Now you will have all the rows you want. To optionally only select an image if there is one, either let your application code handle that or juggle your SELECT clause a bit with an IF-query.