DISTINCT
1)您可以使用or轻松搜索并获得每位客户仅一行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
来维持提供的订单。
编辑另见