Mysql query with single quotation mark in the where clause - mysql

I have this query:
SELECT * FROM tbname WHERE LCASE(title) LIKE '%l\'infinito%'
The value into the table contains slash before quote.
Why the query returns no results?
thanks

The escaping is correct. You actually do not need LCASE since LIKE is not case sensitive (at least not on my Linux system):
mysql> SELECT 'L\'Infinito' LIKE '%l\'infinito%';
+------------------------------------+
| 'L\'Infinito' LIKE '%l\'infinito%' |
+------------------------------------+
| 1 |
+------------------------------------+
1 row in set (0.00 sec)
Maybe you want to search L'Infinito, with an 'n'. Or maybe the title seems to contain a single quote, but it is one of those never sufficiently damned Windows Word reverse English quotes.
Or maybe there is a space in the title after the quote. In many fonts, this is not immediately visible.
L' infinito
Can you search using '%ifinito%' (or '%infinito%'), and verify that the found row does indeed contain a single ASCII quote?
UPDATE
...and finally, maybe the database is wrong. To wit:
mysql> CREATE TABLE catalogo (title varchar (32));
mysql> INSERT INTO catalogo VALUES ('L\'Infinito');
mysql> SELECT * FROM catalogo;
+------------+
| title |
+------------+
| L'Infinito |
+------------+
If you run the same SELECT as before, does MySQL return L'Infinito without escaping? Because if you have instead
+-------------+
| title |
+-------------+
| L\'Infinito |
+-------------+
then the title has been saved wrong, escaping the quote sign TWICE. So there is an escape sign between the L and the quote, and you would have to search for
L\\\'Infinito
to "neutralize" the error.

Try this:
SELECT * FROM tbname WHERE LCASE(title) LIKE '%l\\\'infinito%'

The following query will answer your question:
string s="'infinito";
s=s.Replace("'", "''");
SELECT * FROM tbname WHERE LCASE(title) LIKE '%s%'

Related

SQL query for detect columns with special characters?

here and in a lot of other websites I have find a lot of posts regarding this question but for some strange reason no one works.
I have a Wordpress database and I need to find all the terms contained in wp_terms that have any special character.
In fact I need to find all that contains anything else of number or letter.
Why this doesn't work? The MySQL query return 0 results.
SELECT * FROM wp_terms WHERE name LIKE '%[^0-9a-zA-Z ]%'
You can use REGEXP to find out this. Also the ^must be outside from [].
SELECT * FROM wp_terms WHERE name REGEXP '[^0-9a-zA-Z ]'
Test
MariaDB [(none)]> SELECT "Hello" REGEXP '[^0-9a-zA-Z ]' as resut;
+-------+
| resut |
+-------+
| 1 |
+-------+
1 row in set (0.00 sec)
MariaDB [(none)]> SELECT "-Hello" REGEXP '[^0-9a-zA-Z ]' as resut;
+-------+
| resut |
+-------+
| 0 |
+-------+
1 row in set (0.00 sec)
It does not work because MySQL supports the ANSI version of LIKE. The form that you are using is an extended form associated with SQL Server.
On the other hand, MySQL supports regular expressions which are much more powerful. The regular expression for what you want is:
WHERE name REGEXP '[^0-9a-zA-Z ]'
Note that regular expressions match the pattern anywhere in the string, so you do not need wildcards at the beginning and the end.

mysql strange behavior when inserting data

When inserting data to mysql via the phpmyadmin page, or via python I've seen something I can't explain:
cur.execute("INSERT INTO 28AA507A0500009E (timestamp, temp) VALUES ('2014-01-04 15:36:30',24.44)")
cur.execute("INSERT INTO 28D91F7A050000D9 (timestamp, temp) VALUES ('2014-01-04 15:36:30',24.44)")
cur.execute("INSERT INTO `28012E7A050000F5` (timestamp, temp) VALUES ('2014-01-04 15:36:30',24.44)")
Notice the last entry with the ` around the table name.
The first 2 entry's work fine without the apostrophe.
I can also put the apostrophes around all the table names and it still works.
Why can I remote the apostrophes from the first 2 lines, and not the 3rd one?
The tables are all created equally.
Edit 1:
In due respect to the following comments:
Your explanation is not entirely accurate. There is no alias in
the INSERT statement. I think that the part of the identifier after
28012E7 is just discarded as MySQL tries convert the identifier to
an integer value! – ypercube
these are table names not column names. – Sly Raskal
Well, MySQL sure have discarded the part of the table name identifier. My intention was to bring forward how a identifier name was interpreted when the system could not find it in the list of accessible table names ( I chose column/expression names in my examples ). As the engine interpreted it as a valid number but not as an identifier to represent a table, it threw an exception.
And I chose SELECT to clarify, why the table identifier was rejected for not putting in back quotes. Because it represents a number, it can't be used as an identifier directly, but should be surrounded with back quotes.
MySQL allows to suffix aliases just after numerics, numeric expressions surrounded by braces or literals. To one's surprise, a space between them is optional.
In your case, 28012E7A050000F5 is a valid exponent form ( 28012E7 ) of number 280120000000 suffixed with alias A050000F5. And hence 28012E7A050000F5 can't be used as a column name without back quotes. See following observations:
mysql> -- select 28012E7 as A050000F5;
mysql> select 28012E7A050000F5;
+--------------+
| A050000F5 |
+--------------+
| 280120000000 |
+--------------+
1 row in set (0.00 sec)
Following are some valid examples:
mysql> -- select ( item_count * price ) as v from orders;
mysql> select ( item_count * price )v from orders;
+-----+
| v |
+-----+
| 999 |
+-----+
1 rows in set (0.30 sec)
mysql> -- select ( 3 * 2 ) as a, 'Ravinder' as name;
mysql> select ( 3 * 2 )a, 'Ravinder'name;
+---+----------+
| a | name |
+---+----------+
| 6 | Ravinder |
+---+----------+
1 row in set (0.00 sec)

How can I use the LIKE operator on a list of strings to compare?

I have a query I need to run on almost 2000 strings where it would be very helpful to be able to do a list like you can with the "IN" operator but using the LIKE comparison operation.
For example I want to check to see if pet_name is like any of these (but not exact): barfy, max, whiskers, champ, big-D, Big D, Sally
Using like it wouldn't be case sensitive and it can also have an underscore instead of a dash. Or a space. It will be a huge pain in the ass to write a large series of OR operators. I am running this on MySQL 5.1.
In my particular case I am looking for file names where the differences are usually a dash or an underscore where the opposite would be.
For this task I would suggest making use of RegExp capabilities in MySQL like this:
select * from EMP where name RLIKE 'jo|ith|der';
This is case insensitive match and will save from multiple like / OR conditions.
You could do something like this -
SELECT FIND_IN_SET(
'bigD',
REPLACE(REPLACE('barfy,max,whiskers,champ,big-D,Big D,Sally', '-', ''), ' ', '')
) has_petname;
+-------------+
| has_petname |
+-------------+
| 5 |
+-------------+
It will give a non-zero value (>0) if there is a pet_name we are looking for.
But I'd suggest you to create a table petnames and use SOUNDS LIKE function to compare names, in this case 'bigD' will be equal to 'big-D', e.g.:
SELECT 'bigD' SOUNDS LIKE 'big-D';
+---------------------------+
| 'bigD'SOUNDS LIKE 'big-D' |
+---------------------------+
| 1 |
+---------------------------+
Example:
CREATE TABLE petnames(name VARCHAR(40));
INSERT INTO petnames VALUES
('barfy'),('max'),('whiskers'),('champ'),('big-D'),('Big D'),('Sally');
SELECT name FROM petnames WHERE 'bigD' SOUNDS LIKE name;
+-------+
| name |
+-------+
| big-D |
| Big D |
+-------+
As first step put all static values in any temporary table, this would be lookup dictionary.
SELECT * FROM Table t
WHERE EXISTS (
SELECT *
FROM LookupTable l
WHERE t.PetName LIKE '%' + l.Value + '%'
)
Configure the column containing those 2000 values for full-text searching. Then you can use MySQL's full-text search feature. Refer to their docs
You could use REGEXP instead. It worked like a charm for me
pet_name regexp 'barfy|max|whiskers|champ|you name it'

About mysql regex,how do I search and return string use mysql regex

My table filed's value is "<script type="text/javascript"src="http://localhost:8080/db/widget/10217EN/F"></script>",
I want to analyse this string and fetch the id 10217,how to do use mysql regex?
I know python regex group function can return the id 10217,but i'm not familiar with mysql regex.
Please help me,Thank you very much.
MySQL regular expressions do not support subpattern extraction. You will probably have better luck iterating over all of the rows in your database and storing the results in a new column.
As far as I know, you can't use MySQL's REGEXP for substring retrieval; it is designed for use in WHERE clauses and is limited to returning 0 or 1 to indicate failure or success at a match.
Since your pattern is pretty well defined, you can probably retrieve the id with a query that uses SUBSTR and LOCATE. It will be a bit of a mess since SUBSTR wants the start index and the length of the substring (it would be easier if it took the end index). Perhaps you could use TRIM to chop off the unwanted trailing part.
This query get the Id from the field
SELECT substring_index(SUBSTRING_INDEX(testvar,'/',-3),'EN',1) from testtab;
where as testtab - is table name , testvar - is field name
inner substring get string starts with last 3 / which is
mysql> SELECT SUBSTRING_INDEX(testvar,'/',-3) from testtab;
+----------------------------+
| SUBSTRING_INDEX(testvar,'/',-3) |
+----------------------------+
| 10217EN/F"> |
| 10222EN/F"> |
+----------------------------+
2 rows in set (0.00 sec)
outer substring get
mysql> SELECT substring_index(SUBSTRING_INDEX(testvar,'/',-3),'EN',1) from testtab;
+----------------------------------------------------+
| substring_index(SUBSTRING_INDEX(testvar,'/',-3),'EN',1) |
+----------------------------------------------------+
| 10217 |
| 10222 |
+----------------------------------------------------+
2 rows in set (0.00 sec)

How to know how many words a paragraph contains in MySQL?

What MySQL function can I use?
for example,
What Mysql function can I use?
contains 6 words.
There isn't a built in a function that I know if, but I found this in the comments of MySQL's String Functions documentation:
I was looking for word_count("string") in mysql, finally came up with an user defined function which is very usefull for me, note: I used for actual space.
DROP FUNCTION IF EXISTS word_count;
CREATE FUNCTION word_count (f_string text(5000)) RETURNS smallint(10)
BEGIN
DECLARE new_string text(5000);
WHILE INSTR(f_string,'<space><space>')>0
DO
SET new_string=(select REPLACE(f_string,'<space><space>','<space>'));
SET f_string=new_string;
END WHILE;
RETURN (select LENGTH(TRIM(f_string))-LENGTH(REPLACE(TRIM(f_string),'<space>',''))+1);
END
//
Here is the result
mysql> select word_count("Balaji Devarajan") WORD_COUNT;
+------------+
| WORD_COUNT |
+------------+
| 2 |
+------------+
1 row in set (0.00 sec)
mysql> select word_count(" Balaji Devarajan ") WORD_COUNT;
+------------+
| WORD_COUNT |
+------------+
| 2 |
+------------+
1 row in set (0.00 sec)
mysql> select word_count("Balaji Devarajan") WORD_COUNT;
+------------+
| WORD_COUNT |
+------------+
| 2 |
+------------+
1 row in set (0.01 sec)
There is no function to count words in MySQL (or ANSI SQL, or any other DBMS I'm familiar with).
You could maybe fake it by counting the number of spaces in the text using a string replace:
SELECT LENGTH(colname)-LENGTH(REPLACE(colname, ' ', ''))+1 AS wordcount FROM tablename;
This isn't really a word count but would work as long as every word is separated by exactly one space.
To get better word matching you would need a regex, but there is no regex replace in MySQL so you can't use the replace trick. You could select specifically 6-word long values using a REGEXP/RLIKE match though:
SELECT * FROM tablename WHERE colname RLIKE '^[^[:alnum:]]*[[:alnum:]]+([^[:alnum:]]+[[:alnum:]]+){5}[^[:alnum:]]*$';
Either way, this is slow. It will have to do a string replace or regex match on every row of the table every time you do the query. If number-of-words is a query you are doing often you will want to optimise (denormalise) the table by adding a (possibly indexed) column to store the number of words.