我需要在以下条件下搜索MySQL数据库:
1)如果找到关键字的任何完全匹配,请返回行数和结果与完全匹配。
2)如果找不到完全匹配,则返回行数和结果,并进行部分匹配。
例如,如果关键字为cake
,并且该表具有以下行,则搜索应仅返回第1行和第5行。
1| cake
2| pancake
3| cupcake
4| fruitcake
5| cake
6| pie
但是,如果仅存在以下行,则搜索应仅返回行2-4。
2| pancake
3| cupcake
4| fruitcake
6| pie
在两个查询中执行此操作非常简单,例如:
SELECT SQL_CALC_FOUND_ROWS fields FROM table WHERE word = `cake`
//PHP checks for number of rows, if 0, do second query
SELECT SQL_CALC_FOUND_ROWS fields FROM table WHERE word LIKE '%cake%'
问题:要减少前往数据库的行程,有没有办法在单个查询中执行此操作?
我能想出的最佳解决方案是通过OR匹配,使用ORDER BY来支持完全匹配。但是,如果找到完全匹配,要切断部分匹配,则需要遍历结果,如果完全匹配返回2,000个结果并且部分匹配返回5,000个以上,则不可行,但我只想显示前25个,同时仍然显示2,000计数。
答案 0 :(得分:2)
编辑3:
following确实有效:
SELECT
COALESCE(NULLIF(COUNT(exact.Id), 0), COUNT(partial.Id))
FROM
Test AS partial
LEFT JOIN
Test AS exact ON exact.Id = partial.Id AND exact.Name = 'pi'
WHERE
partial.Name LIKE '%pi%'
我在这里删除了我的上一篇文章,因为它错了。
编辑4:
以下是用TSQL编写的(我不知道正确的MySql语法)并返回实际的行(您可以将它包装在MySql服务器上的StoredProcedure中):
CREATE TABLE #Result (Id int, Name nvarchar(max));
INSERT INTO #Result
SELECT * FROM #YourCakeTable WHERE Name = 'cake'
if(FOUND_ROWS() = 0)
INSERT INTO #Result
SELECT * FROM #YourCakeTable WHERE Name like '%cake%'
SELECT * FROM #Result
答案 1 :(得分:0)
我不确定MYSQL语法,但你可以这样做:
SELECT (CASE WHEN Exact.Apparence IS NULL THEN Partial.Apparence ELSE Exact.Apparence END) as Apparence FROM
(SELECT COUNT(word) as Apparence FROM Table WHERE word='cake') as Exact INNER JOIN
(SELECT COUNT(word) as Apparence FROM Table WHERE word like '%cake%') as Partial ON 1=1
让我知道它是否有助于你
答案 2 :(得分:0)
SELECT word, count(*) as ExactMatches,
if(count = 0, (SELECT count(*) from table WHERE word LIKE '%word%' order by word), NULL) as PartialMatches
FROM table
order by word
我认为这里会发生的是你会得到你的
word|count exacts|count partials|
cake|100| null
cake|0| 50
答案 3 :(得分:0)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
~/installed/python/demuxDelayer/demuxDelayer_v2.py in <module>
1 for d in 'today yesterday'.split():
2 for k in d_day_format.keys():
----> 3 globals()[f"{d}_{k}"] = eval(d).eval(k).format(f"{d_day_format[k]}")
AttributeError: 'datetime.date' object has no attribute 'eval'