2

Is it possible in MYSQL to do a partial match but the opposite way round to how this is normally done..

I.E I have a website for checking.... voucher codes

A user types "WUD092050549E" and hits search

I want the database to return... any row with column_x matching

  • "WUD092050549E" - exact match

  • "WUD0920" - 7 character match

  • "WUD0" - 4 character match

BUT NOT

  • "WUD039540" - 4 character match, then incorrect

  • "123213WUD092050549E2334" - incorrect characters, then match

Essentially where the row matches 4 or more characters (in the same sequence) with no mistakes

I know exact matches can be achieved by.. "SELECT * WHERE column_x="WUD092050549E"

For myself I ideally want to sort exact matches, then if none were found other less accurate matches (so two queries possibly)

4

2 回答 2

0

目前尚不清楚规范是什么。

如果要检查整个匹配,前七个字符或前四个字符:

SELECT t.voucher_code='WUD092050549E' AS exact_match
     , t.*
  FROM mytable t
 WHERE t.voucher_code = 'WUD092050549E'
    OR t.voucher_code = LEFT('WUD092050549E',7)
    OR t.voucher_code = LEFT('WUD092050549E',4)

如果您想要匹配任何长度的优惠券代码,您可以列举所有可能性:

SELECT t.voucher_code = 'WUD092050549E' AS exact_match
     , t.*
  FROM mytable t
 WHERE t.voucher_code = 'WUD092050549E'
    OR t.voucher_code = LEFT('WUD092050549E',11)
    OR t.voucher_code = LEFT('WUD092050549E',10)
    OR t.voucher_code = LEFT('WUD092050549E',9)
    OR t.voucher_code = LEFT('WUD092050549E',8)
    OR t.voucher_code = LEFT('WUD092050549E',7)
    OR t.voucher_code = LEFT('WUD092050549E',6)
    OR t.voucher_code = LEFT('WUD092050549E',5)
    OR t.voucher_code = LEFT('WUD092050549E',4)

更慢,但更简洁:

SELECT t.voucher_code
     , t.*
  FROM mytable t
 WHERE t.voucher_code = LEFT('WUD092050549E',CHAR_LENGTH(t.voucher_code))

但我不确定我是否理解规范,所以这可能与您正在寻找的内容相去甚远。

于 2012-08-31T22:32:14.207 回答
0

关于什么:

SELECT 1 from DUAL 
WHERE column_x LIKE 'WUD092050549E%'
or INSTR('WUD092050549E', column_x ) > 0

你可以在这里查看

于 2012-08-31T22:20:48.687 回答