SQL SELECT命名LIKE $ name但不是两次完全相同的名称

时间:2013-09-13 01:47:09

标签: sql sql-like

我正在使用此SQL查询来查看表并搜索客户名称并返回该行的id和日期列:

SELECT custName, date, id FROM booking
WHERE custName LIKE '%$s'
OR custName LIKE '$s%'

($ s是PHP变量)

如果我正在寻找John Dorian,我可以输入$ s作为John的名字,或者姓Dorian,我的职能会找到他。我的问题是John Dorian可能出现在多行中,如果是这种情况,我希望查询只返回最近一行(使用日期列来计算出来)。

IE如果我的表看起来像这样,$ s = John:

(custName, date, id)
John Dorian - 2013/01/01 - 1
John Doe - 2013/01/02 - 2
John Dorian - 2013/01/10 - 3

我希望我的查询返回

John Doe - 2013/01/02 - 2
John Dorian - 2013/01/10 - 3

4 个答案:

答案 0 :(得分:2)

怎么样:

SELECT custName, date, id 
FROM booking b
INNER JOIN
(
    SELECT max(date) MaxDate, custName
    FROM booking
    WHERE custName LIKE '%$s%'
    GROUP BY custName
) bm
  ON b.custName = bm.custName
  AND b.date = bm.maxDate
WHERE custName LIKE '%$s%'
ORDER BY b.date DESC

答案 1 :(得分:1)

1)您可以使用DISTINCTGROUP 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%';

P.S。

以下看似有希望,有时甚至可能给出正确的结果,但不能保证有效。

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来维护提供的订单。

编辑另请参阅

答案 2 :(得分:0)

我认为你需要在custName列上有一个独特的。虽然我自己没有尝试过,但我认为BadWolf的回答会返回名为'John Dorian'的行:

SELECT distinct(custName), date, id FROM booking WHERE 
custname LIKE '%$s%' 
GROUP BY custName, date, id
ORDER BY date DESC

答案 3 :(得分:0)

乍一看,我认为这是一个简单的问题,但我错了。

我只能通过以下陈述来解决。

select * from 
   (SELECT custName, date, id FROM booking 
          WHERE custName LIKE '%$s' OR 
          custName LIKE '$s%' order by date desc) as t 
   group by (t.custName) order by date ;

它可能有其他更好的解决方案。