Forum Moderators: open

Message Too Old, No Replies

MySQL select not all field

         

texasguy

9:11 pm on Mar 19, 2009 (gmt 0)

10+ Year Member



I have several fields that include something like Thisismyexample (97)

When I show the results on a page, I want to show the Thisismyexample but I want to leave off everything after the (

Is this possible? Suggestions?

Thanks

rocknbil

9:17 pm on Mar 19, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



welcome aboard texasguy, what does your select statement look like?

If (97) is actually part of what's stored in the field, you'd do a regular expression after extracting it, like

$field =~ s/\s*\(\d+\)\s*$//; # perl
$field = preg_replace("/\s*\(\d+\)\s*$",'',$field); # php

But it may have to do with the way you're selecting, normally
select [comma-separated field list] from table;

texasguy

9:34 pm on Mar 19, 2009 (gmt 0)

10+ Year Member



(97) is actually stored in the field. the field currently looks like:

Thisismyexample (97)

and when I do a query (in this case, to put into a graph) ... I don't need the number. So I need to leave off the (97). Make sense?

rocknbil

5:32 pm on Mar 20, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



. . and when I do a query (in this case, to put into a graph) ... I don't need the number.

I think there might be a select to extract the data without the (number,) but overall it might be simpler to get the data and alter it after extraction.

To select, there are a number of ways. You'd have to experiment with what's fastest and easiest to automate in your code:

select field from table where field like 'ThisIsMyExample%';

Combining like and % is like a wild card, "Starts with 'ThisIsMyExample' and anything that follows it." Putting % at the front is the same concept.

A regular expression might be slower but would be more specific:

select field from table where field regexp '^ThisIsMyExample[[:blank:]]*\([[:digit:]]+\)[[:blank:]]*$';

which means
- ^ starts with
- followed by ThisIsMyExample
- [[:blank:]]* followed by zero or more spaces
- followed by ( (escaped with (, which is a special character in regexps)
- [[:digit:]]+ followed by one or more digits
followed by )
- [[:blank:]]* followed by zero or more spaces
- $ end of pattern (nothing after this)

Although, there are different approaches to case-sensitivity when doing a regexp in mysql, see the documentation [dev.mysql.com] for the gory details.

Frank_Rizzo

6:16 pm on Mar 20, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




If the number is always at the end then you could do this:

SELECT SUBSTRING_INDEX(YOUR_FIELD, '(',1);

e.g. using a text example

SELECT SUBSTRING_INDEX('Thisismyexample (97)', '(',1);

returns

Thisismyexample

If you want to do it in php code

$field = $row['YOUR_FIELD'];
if(strpos($field, '(')) {
$field = substr($field, 0, strpos($field, '('));
}