1) Using DISTINCT
or GROUP BY
you can easily find and get only one row for each client:
SELECT DISTINCT custName FROM booking WHERE custName LIKE '%$s' OR custName LIKE '$s%';
or
SELECT custName FROM booking WHERE custName LIKE '%$s' OR custName LIKE '$s%' GROUP BY custName;
2) You can get the maximum date by linking the aggregation function (i.e. MAX
) with GROUP BY
SELECT custName, MAX(date) as date FROM booking WHERE custName LIKE '%$s' OR custName LIKE '$s%' GROUP BY custName;
3) Finally, you can get the full row of the table by adding the results to the original table:
SELECT b.custName, b.date, b.id FROM booking AS b INNER JOIN (SELECT custName, MAX(date) AS maxDate FROM booking WHERE custName LIKE '%$s' OR custName LIKE '$s%' GROUP BY custName ) AS gb ON b.custName = gb.custName AND b.date = gb.maxDate;
or (maybe slower):
SELECT b.custName, b.date, b.id FROM booking AS b INNER JOIN (SELECT custName, MAX(date) AS maxDate FROM booking GROUP BY custName ) AS gb ON b.custName = gb.custName AND b.date = gb.maxDate WHERE b.custName LIKE '%$s' OR b.custName LIKE '$s%';
ps
The following may seem promising and can sometimes give the right results, but performance is not guaranteed.
SELECT * FROM ( SELECT custName, date, id FROM booking WHERE b.custName LIKE '%$s' OR b.custName LIKE '$s%' ORDER BY date DESC ) AS t GROUP BY custNAME;
Unfortunately, you cannot rely on GROUP BY
to support your order.
EDIT See also
source share