7
SELECT * 
FROM `thread` 
WHERE forumid NOT IN (1,2,3) AND IF( LEFT( title, 1) = '#', 1, 0)
ORDER BY title ASC

I have this query which will select something if it starts with a #. What I want to do is if # is given as a value it will look for numbers and special characters. Or anything that is not a normal letter.

How would I do this?

Jason
  • 51,583
  • 38
  • 133
  • 185
Ben Shelock
  • 20,154
  • 26
  • 92
  • 125

3 Answers3

21

If you want to select all the rows whose "title" does not begin with a letter, use REGEXP:

  SELECT * 
    FROM thread 
   WHERE forumid NOT IN (1,2,3)
     AND title NOT REGEXP '^[[:alpha:]]'
ORDER BY title ASC
  • NOT means "not" (obviously ;))
  • ^ means "starts with"
  • [[:alpha:]] means "alphabetic characters only"

Find more about REGEXP in MySQL's manual.

Josh Davis
  • 28,400
  • 5
  • 52
  • 67
  • 1
    working url to regexp manual is https://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp – dsomnus Mar 07 '14 at 16:36
1

it's POSSIBLE you can try to cast it as a char:

CAST('#' AS CHAR)

but i don't know if this will work for the octothorpe (aka pound symbol :) ) because that's the symbol for starting a comment in MySQL

Jason
  • 51,583
  • 38
  • 133
  • 185
  • Im a real MySQL newbie. That NOT IN clause is waayy over my head just to put it into context. Could you explain a little more please :) – Ben Shelock Jul 31 '09 at 18:16
  • just replace `AND IF( LEFT( title, 1) = '#', 1, 0)` with `AND IF( LEFT( title, 1) = CAST('#' AS CHAR), 1, 0)`, but like i said, i don't know if it will work w/octothorpes – Jason Jul 31 '09 at 18:20
  • ah, so... sorry, thought i'd give it a shot – Jason Jul 31 '09 at 18:30
1
  SELECT t.* 
    FROM `thread` t
   WHERE t.forumid NOT IN (1,2,3) 
     AND INSTR(t.title, '#') = 0
ORDER BY t.title

Use the INSTR to get the position of a given string - if you want when a string starts, check for 0 (possibly 1 - the documentation doesn't state if it's zero or one based).

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502