0

我必须创建一个 sql 查询来获取所有用户的名字、中间名或姓氏,其中包含字符“|”。所以我做了类似的事情:

SELECT two.id, 
       two.username, 
       one.firstname, 
       one.middlename, 
       one.lastname 
FROM table_one one INNER JOIN table_two two ON two.id = one.id
WHERE one.firstname LIKE '%|%' 
OR one.middlename LIKE '%|%' 
OR one.lastname LIKE '%|%'

此查询在大约有一千个配置文件的测试环境中运行良好,但在包含数十万个配置文件的生产环境中超时,如果不是接近一百万个。

我们正在运行 DB2,版本 8.2

4

2 回答 2

2

您可以尝试拆分搜索以删除OR因性能不佳而臭名昭著的 :

SELECT
  two.id, 
  two.username, 
  one.firstname, 
  one.middlename, 
  one.lastname 
FROM (
  SELECT id, firstname, middlename, lastname
  FROM table_one 
  WHERE one.firstname LIKE '%|%'
  UNION
  SELECT id, firstname, middlename, lastname
  FROM table_one 
  WHERE one.middlename LIKE '%|%'
  UNION
  SELECT id, firstname, middlename, lastname
  FROM table_one 
  WHERE one.lastname LIKE '%|%'
) one
INNER JOIN table_two two ON two.id = one.id

在每个名称列上都有一个索引,每个列都有可能在单独的联合查询中使用。

使用 onUNION可以方便地丢弃重复项,因此多个名称列包含管道字符的情况不会导致重复输出。

于 2013-07-09T15:02:23.147 回答
0

尝试

SELECT two.id, 
       two.username, 
       one.firstname, 
       one.middlename, 
       one.lastname 
FROM table_one one INNER JOIN table_two two ON two.id = one.id
WHERE POSITION('|',concat(one.firstname,one.middlename,one.lastname),OCTETS)>0

或者

SELECT two.id, 
       two.username, 
       one.firstname, 
       one.middlename, 
       one.lastname 
FROM table_one one INNER JOIN table_two two ON two.id = one.id
WHERE POSITION('|',one.firstname,OCTETS)+POSITION('|',one.middlename,OCTETS)+POSITION('|',one.lastname),OCTETS)>0
于 2013-07-09T15:03:40.363 回答