简体   繁体   中英

Using UNION instead of OR in MySQL?

I have a PK of

(id1, id2, col4, col5)

This query successfully uses my index except for the last LIKE (which is very usable):

SELECT *
FROM table1
WHERE id1 = 2 AND id2 = 1 AND col4 LIKE 'min%' AND col4 LIKE '%hou%'

I'm wondering how to rewrite this query (or if it's possible) so it too uses the index at least for part of the query. I've unsuccessfully tried several ways using UNION, but here's what I started with:

SELECT *
FROM table1
WHERE id1 = 2 AND id2 = 1 AND col4 LIKE 'min%'
   OR col5 LIKE 'min%' AND (col4 LIKE '%hou%' OR col5 LIKE '%hou%')

Thanks for taking a look.

I doubt that rewriting the query would help.
The second part of your condition requires to read the whole content of the table anyway.

You could try to create another index on col5 , since documentation states that

The index also can be used for LIKE comparisons if the argument to LIKE is a constant string that does not start with a wildcard character.

which is exactly what you need: col5 LIKE 'min%'

sorry, I can't understand second query. if first query works well and performance is poor, then Full Text Search is needed. MyISAM has this feature.

But InnoDB does not have. In this case, you can do it by yourself. let's implement simple search engine. segment index is required. to search col5 's value efficiently.

tbl1(tbl1_idx, id1, id2, col4, col5);
segment_tbl(tbl1_idx, col_no, val);

insert into tbl1 values('row1', '2', '1', 'minute', 'foo hour');

insert into segment_tbl values('row1', 5, 'foo');
insert into segment_tbl values('row1', 5, 'hour');

SELECT *
FROM tbl1 JOIN segment_tbl USING(tbl1_idx)
WHERE tbl1.id1 = 2 and tbl1.id2 = 1
  AND col4 LIKE 'min%'
  AND segment_tbl.col_no = 5
  AND segment_tbl.val LIKE 'hou%';

There is still problem. if col5's value is 'foohour', this does not work. So how to segment is key point. saving all possible character sequence is the best. like 'oohour', 'ohour', 'hour', 'our', 'ur', 'r', but this consumes so much space. in the earlier 2000, there was no sutable open source search engine. So I did as explained above. It had worked well. but there was plenty of rows.

Simply I suggest MyISAM's FTS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM