DISTINCT
1)またはを使用して、顧客ごとに 1 つの行のみを簡単に検索して取得できますGROUP BY
。
SELECT DISTINCT custName
FROM booking
WHERE custName LIKE '%$s' OR custName LIKE '$s%';
また
SELECT custName
FROM booking
WHERE custName LIKE '%$s' OR custName LIKE '$s%'
GROUP BY custName;
2) 集計関数 (つまりMAX
) をGROUP BY
SELECT custName, MAX(date) as date
FROM booking
WHERE custName LIKE '%$s' OR custName LIKE '$s%'
GROUP BY custName;
3) 最後に、結果を元のテーブルに結合して、完全なテーブル行を取得できます。
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;
または(おそらく遅い):
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
以下は有望に見えるかもしれませんし、時には正しい結果が得られるかもしれませんが、動作することは保証されていません.
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;
GROUP BY
残念ながら、提供された順序を維持するために に頼ることはできません。
編集こちらもご覧ください