How to define this search?
I have customer codes stored in a table. Customer codes are stored as:
CSC 1234
CSC 003E
CSC AAF8
etc.
I need to find the first code that has numerical values only.
I'm using the following sentence:
SELECT TOP 1 *
FROM Customer
WHERE custcode LIKE 'CSC [1-9][1-9][1-9][1-9]'
ORDER BY c开发者_如何学Custcode;
But it gives 0 results. What is wrong?
LIKE
is for wildcards, not regexes.
This is really clear in the documentation — why are you not reading it?!
Perhaps you're after REGEXP
:
SELECT TOP 1 *
FROM Customer
WHERE custcode REGEXP 'CSC [1-9][1-9][1-9][1-9]'
ORDER BY custcode;
Also, I think you mean LIMIT 1
with MySQL (TOP 1
is from Microsoft SQL Server), and we can condense that regex:
SELECT *
FROM Customer
WHERE custcode REGEXP 'CSC [1-9]{4}'
ORDER BY custcode
LIMIT 1;
Update sllev makes a very good point that you might mean [0-9]
rather than [1-9]
. Adapt appropriately.
(And it's "query", not "sentence".)
SELECT *
FROM Customer
WHERE custcode REGEXP 'CSC [[:digit:]]{4}';
ORDER BY custcode
LIMIT 1;
Never having been one to shy away from spoon-feeding...
SELECT *
FROM Customer
WHERE custcode REGEXP 'CSC [1-9]{4}'
ORDER BY custcode;
or without regex:
SELECT * FROM Customer WHERE custcode >= 'CSC 0000' AND custcode <= 'CSC 9999' ORDER BY custcode LIMIT 1;
Also, will use the index of custcode(if is defined) for filtering.
精彩评论