0

I have two tables (I'll list only fields that I want to search)

MySQL version: 5.0.96-community

Table 1: Clients (860 rows)
ID_CLIENT (varcahar 10)
ClientName (text)

Table 2: Details (22380 rows)
ID_CLIENT (varchar 10)
Details (varchar 1000)

The Details table can have multiple rows from the same client.

I need to search into those two tables and retrive the ids of clients that match a search value.

If i have a search value "blue" it has to match CLientName (ex the Blueberries Corp), or the Details in the second table (ex "it has a blue logo)

The result should be a list of client id's that match the criteria.

If I make a query for one table, it takes a decent time

#0.002 sec
select a.`ID_CLIENT` from clienti a
where 
a.`ClientName` LIKE '%blue%' 


#0.1 sec
SELECT b.`ID_CLIENT` FROM Details b
WHERE b.`Details` LIKE  '%blue%'
GROUP BY b.`GUID_CLIENT` 

But if I try to join those two queries it takes ages.

My questions(s)

  1. What's the best way of doing what I need here, to get a list of ID-s based on the search result from both tables

  2. What to change to improve search performance in the Details table, I know that %..% is not fast, but I need partial matches too.

Edit (based on the answers)

#~0.2 sec
(SELECT a.`ID_CLIENT` FROM `clienti` a  where a.`ClientName` like '%blue%')  
union
(SELECT distinct b.`ID_CLIENT` FROM `Details` b where b.`Details` like '%blue%')

It returns a list of IDs from both tables filtred by the search value.

Edit 2: final query

And with that list of ids I can filter the client table, to get only the clients that are in boths tables based on their id

select cl.`ID_CLIENT`, `ClientName`, `OtherField`
from clients cl 
join 
((SELECT a.`ID_CLIENT` FROM `clients` a  where a.`ClientName` like '%blue%')
union
(SELECT distinct b.`ID_Client` FROM `Details` b where b.`Detail` like '%blue%' )) rez 
on cl.`ID_CLIENT` = rez.`ID_CLIENT` 
4

3 回答 3

1

如果您的两个查询有效,只需使用union

select a.`ID_CLIENT`
from clienti a
where  a.`ClientName` LIKE '%blue%' 
union
SELECT b.`ID_CLIENT`
FROM Details b
WHERE b.`Details` LIKE '%blue%';

union删除所有重复项,因此您不需要单独的group by查询。

为什么两个表的两个搜索字符串不同?这个问题建议在他们两个中搜索blue

如果个别查询表现不佳,您可能需要切换到全文索引。

于 2014-02-25T18:24:16.323 回答
1

如果两个查询都按您的意愿运行,只需将结果合并在一起即可。这比不能有效使用索引的查询上的“或”快得多,它还允许您删除同一语句中的重复项。

于 2014-02-25T18:18:23.113 回答
1

Divide et impera:创建两个子查询。

在第一个子查询中,根据 client_id 将带有详细信息的客户端左连接,过滤客户端名称为 '%xxxxx%' 的行值

然后是另一个子查询,将详细信息与客户端连接(但在输出投影中保持相同的字段顺序),对详细信息文本字段进行过滤。然后从两个子查询中创建一个联合查询,最后从这个联合中创建一个select distinct *

最终架构:

选择不同的 * from (subquery1 union subquery2)

这似乎是一个非常缓慢和愚蠢的“手动查询计划优化”,试一试,让我们知道它有效!

于 2014-02-25T18:18:24.227 回答