I am trying to write an SQL query that will sort based on a date (which is an INTEGER in the database) that could be in 1 of 2 tables, or both.
The fields in the tables this is in regards to are:
assignments:
– id
– id_lead
– date_assigned
leads:
– id
– date_added
the tables have other fields, but they do not apply to this question.
Now what i want, is if there is no assignments for the lead, I want the “date_sort” variable to be the date_added value of the lead. if there IS an assignment for the lead, i want it to be the date_assigned value of the assignment.
my problem is, using my query just doesn’t show any of the leads that do not have an assignment in my results list.
heres my query im working on:
$pagi_sql = "select
l.id, l.id_infusionsoft, l.name_first, l.name_last, l.postcode, a.website as a_website, l.website as l_website, l.date_added,
a.id_dealership, a.id_lead, a.id as id_assign, a.date_assigned,
d.name as dealership,
if(a.id = null, l.date_added, a.date_assigned) as date_sort
from `leads` as l
left join `assignments` as a on (a.id_lead = l.id)
left join `dealerships` as d on (d.id = a.id_dealership)
$where
order by date_sort desc";
heres my original query, which works, but is not sorting the way i want it to:
$pagi_sql = "select
l.id, l.id_infusionsoft, l.name_first, l.name_last, l.postcode, a.website as a_website, l.website as l_website, l.date_added,
a.id_dealership, a.id_lead, a.id as id_assign, a.date_assigned,
d.name as dealership
from `leads` as l
left join `assignments` as a on (a.id_lead = l.id)
left join `dealerships` as d on (d.id = a.id_dealership)
$where
order by l.date_added desc";
leads can have multiple assignments….i think this is the problem…but i cant figure out how to get it to sort the way i want.
should i change these up, so that im selecting from the assignments table instead? but then i run into the problem of, how do i show the unassigned leads in the same table sorted by the date_added/date_assigned?
any help would be awesome.
Change this line:
To this:
The reason why the first line isn’t sorting the way you want it to is because the false condition of
IFis always being executed sinceNULLis an unknown value and cannot equal to anything, not even itself.You must use
IS NULLinstead of= NULL.Read my answer to this question for more insight on
NULLvalues.Edit: If you want to be more succinct, you can do:
Th
COALESCE()function will return the first non-NULLargument.If you have no need to display the value of
date_sort, you can even put it straight into theORDER BYclause: