There is a table with fields name, age, city and state. Now I need to select rows based on city name. The value of the column city is surrounded with ", for example "LA".
How can I write a SELECT statement for getting data based on city.
\" is the escape combination for double quotes:
SELECT * FROM mytable WHERE city = '\"LA\"';
See MySQL documentation "String Literals".
Just suggestion, if you are collecting and storing the information in the table to be queried later (ie you are in control of the input), try to clean the data up before storing it to make it easier to query?
If the input has quotes and white space, clean that before inserting the values into the table. Use programming to do this, or mySQL: TRIM() and REPLACE() to remove the characters that might make a query hard to build and then store the resulting value into the table.
Of course, if you do not have control of the input data, that is where the answers above and the challenge to a programmer begins, trying to figure out the different input possibilities and dealing with that.
SELECT *
FROM table1
WHERE city LIKE '%LA%'
or
SELECT *
FROM table1
WHERE city REGEXP '^[[:space:]]*LA[[:space:]]*$'
Related
I have a MySQL column that contains phone numbers, the problem is that they're in different formats, such as:
2125551212
212-555-1212
(212)5551212
I'd like to know if it's possible to take the existing 10 digits, remove the formatting, and change them all to this format: (212) 555-1212
Not a duplicate, as I'm looking to update several thousand entries instead of masking new entries.
Unfortunately, no REGEXP_MATCHES() or TRANSLATE() function comes with standard MySQL installation (they do with Postgres), so you could do this a way which I find really dirty, but it works.
First you cleanse your column by removing characters that aren't numbers using replace()
Then you take several parts of the string to separate them out using substr()
Finally, you concatenate them adding symbols between your substrings with concat()
If you have any more characters that you need truncate, just add another replace() on top of 3 already existing.
Sample data
create table nums ( num text );
insert into nums values
('2125551212'),
('212-555-1212'),
('(212)5551212');
Query formatting your data
select
num,
concat('(',substr(num_cleansed,1,3),') ',substr(num_cleansed,4,3),'-',substr(num_cleansed,7)) AS num_formatted
from (
select
num,
replace(replace(replace(num,'(',''),')',''),'-','') as num_cleansed
from nums
) foo
Result
num num_formatted
2125551212 (212) 555-1212
212-555-1212 (212) 555-1212
(212)5551212 (212) 555-1212
Click here SQLFiddle to preview output.
I'm leaving UPDATE statement as a homework for the reader.
Some advise on this issue:
select
concat(MySourceTable,',',sid,'X',gid,'X',qid) as MySourceFieldname
from
MySchemaTable
where
SomeCriteria;
Using the upper Statement I get a list (one column only) of fieldnames.
How can I transform this to be shown in horizontal (Fields next to each other) position, separated by comma
I want to produce a 'normal" SELECT-Statement for further use.
#amixdon
Input is :
select concat('shape_survey_990113',sid,'X',gid,'X',qid) as lsfield -- <=MySourceFieldname
from shape_questions -- <=MySchemaTable i.e. kind of dictionary
where question='result' -- <=SomeCriteria
and sid=990113
and language='en'
order by lsfield;
Result of Input looks like this (e.g.)
lsfields
---------
shape_survey_990113.990113X468X729,
shape_survey_990113.990113X469X733,
shape_survey_990113.990113X470X737,
....,
Explanation: sid, gid, qid are numeric contents taken from a table that is comparable to a dictionary. This is the source system which I want to select information from (cannot be changed). It is an opensource survey tool. Within this table all information for each survey is handled (numeric value 990113 is identifiying one special survey out of many. The concat above ist the final field name that holds the answers to the questions.
The 'shape_survey_990113' is the table to select the firlds from:
This select result should look like this an can be written to some variable
(e.g. SET #MyFields =...)
shape_survey_990113.990113X235X476, shape_survey_990113.990113X235X484, shape_survey_990113.990113X235X496
..to be used in the next step to make up a real select statement like:
concat('SELECT ', #MyFields, ' FROM shape_survey_991103;')
Unfortunately i cannot upload a screenshot fort this, not enough reputation....
There's nothing sacred, and quite a bit profane, about that CONCAT(). Lose it. And lose the quoted commas. Like so.
select
MySourceTable, sid, gid, qid
from
MySchemaTable
where
SomeCriteria;
Simple as can be.
I have one value, that represents a zip code.
I need to see which city belongs to this zip code by comparing the given value with the values in two columns of the DB.
This is my _cities table:
city (name of the city, VARCHAR)
zipcode_start (the first zip code available, VARCHAR )
zipcode_end ( the last zip code available, VARCHAR ).
Where I leave zipcodes are numbered in sequence.
So if I have for example: city = Rome, zipcode_start = 00118 and zipcode_end = 00199 and the given zipcode is 00119, how do I get the city Rome from the DB?
00119 in this case is included in the sequence 00118 - 00199, so the DB should return Rome.
I can do this in many ways with PHP, but I am looking for an elegant way to do it directly with a SQL statement.
Is this possible?
Thanks for any help
I'd use BETWEEN, or if you don't like that, you can use >= and <=. And if you prefer joins over where clauses, you can even join on an inequality sometimes.
For example,
select city
from my_cities
where zipcode between zipcode_start and zipcode_end
You have to deal with getting the variable into that statement, but I get the impression that you can handle that part already. Is this what you are trying to do? I sort of doubt it, but that's all I get out of your question.
My user table has a column "name" which contains information like this:
Joe Lee
Angela White
I want to search for either first name or last name efficiently. First name is easy, I can do
SELECT * FROM user WHERE name LIKE "ABC%"
But for last name, if I do
SELECT * FROM user WHERE name LIKE "%ABC"
That would be extremely slow.
So I am thinking about counting the characters of the input, for example, "ABC" has 3 characters, and if I can search only the last three characters in name column, that would be great. So I want something like
SELECT * FROM user WHERE substring(name, end-3, end) LIKE "ABC%"
Is there anything in MySQL that can do this?
Thanks so much!
PS. I cannot do fulltext because our search engine doesn't support that.
The reason that
WHERE name LIKE '%ith'
is a slow way to look for 'John Smith' by last name is the same reason that
WHERE Right(name, InStr(name, ' ' )) LIKE 'smi%'
or any other expression on the column is slow. It defeats the use of the index for quick lookup and leaves the MySQL server doing a full table scan or full index scan.
If you were using Oracle (that is, if you worked for a formerly wealthy employer) you could use function indexes. As it is you have to add some extra columns or some other helping data to accelerate your search.
Your smartest move is to split your first and last names into separate columns. Several other people have pointed out good reasons for doing that.
If you can't do that you could try creating an extra column which contains the name string reversed, and create an index on that column. That column will have, for example, 'John Smith' stored as 'htimS nhoJ'. Then you can search as follows.
WHERE nameReversed LIKE CONCAT(REVERSE('ith'),'%')
This search will use the index and be decently fast. I've had good success with it.
You're close. In MySQL you should be able to use InStr(str, substr) and Right(str, index) to do the following:
SELECT * FROM user WHERE Right(name, InStr(name, " ")) LIKE "ABC%"
InStr(name, " ") returns the index of the Space character (you may have to play with the " " syntax). This index is then used in the Right() function to search for only the last name (basically; problems arise when you have multiple names, multiple spaces etc). LIKE "ABC%" would then search for a last name starting with ABC.
You cannot use a fixed index as names that are more than 3 or less than 3 characters long would not return properly as you suggest.
However, as Zane said, it's a much better practise to use seperate fields.
If it is a MyIsam table, you may use Free text search to do the same.
You can use the REGEXP operator:
SELECT * FROM user WHERE name REGEXP "ABC$"
http://dev.mysql.com/doc/refman/5.1/en/regexp.html
I've to ask your help to solve this problem.
My website has a search field, let's say user writes in "Korg X 50"
In my database in table "products" i have a filed "name" that holds "X50" and a field "brand" that hold "Korg". Is there a way to use the UNION option to get the correct record ?
And if the user enters "Korg X-50" ?
Thank you very much !
Matteo
May be you should use full-text search
SELECT brand, name, MATCH (brand,name) AGAINST ('Korg X 50') AS score
FROM products WHERE MATCH (brand,name) AGAINST ('Korg X 50')
As far as I understand you don't need UNION but something like
SELECT * FROM table1
WHERE CONCAT(field1, field2) LIKE '%your_string%'
On client side you get rid of all characters (like space, hyphen, etc) in your_string that appears in user input and cannot be in field1 or field2.
So, user input Korg X 50 as well as Korg X-50 becomes KorgX50.
you will need to get some form of searchable text.
either parse out the input for multiple key words and match each separately, or perhaps try to append them all together and match to the columns appended in the same way.
you will also need either a regex, or maybe a simpler search and replace to get rid of spaces and dashes after the append before the comparison.
in general, allowing users to search for open ended text strings is more complicated than 'what union do i use'... you will ideally also be worried about slight misspellings and capitalization, and keyword order.
you may consider pulling all keywords out from your normal record into a separate keyword list associated with each product, then use that list to perform your searches.
If you do not want to parse user input and use as it is, then you will need to use a query like this
select * from products where concat_ws(' ',brand,name) = user_input -- or
select * from products where concat_ws(' ',brand,name) like %user_input%
However, this query won't return result if user enters name "Korg X-50" and your table contains "Korg" and "X50", then you need to do some other thing to achive this. You may look at http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_soundex however it won't be a complete solution. Look for text indexing libraries for that ex: lucene