Performance in rlike expression or alternate query? - mysql

I am doing a series of updates on some tables after I import them from tab-separated values. The data comes with dates in a format I do not like. I bring them in as strings, manipulate them so that they are in the same format as MySQL dates and then convert the column. Or sometimes not, but I want them to be like MySQL dates even if they are strings.
They start out like '1/4/2013 12:00:00 AM' or '11/4/2012 2:37:45 PM'.
I turn these into '2013-01-04' (usually, since times are present even when the original schema clearly specifies dates only) and '2012-11-04 14:37:45'.
I am using rlike. And this does not use indexes? Wow. That sucks.
But already, for each column, I have to use 4 updates to handle the different cases ('1/7', '2/13', '11/2', '12/24'). If I did these using like, it might take 16 different updates for each column....
And, if I am seeing it right, I cannot even get positional parameters out of the rlike expression, yes? You know, the part of the expression wrapped in parentheses that becomes $1 or $2....
So, it seems as though it is going to be quicker to pre-process the tsv file with perl. Really? Wow. Again, this sucks.
Any other suggestions? I cannot have this taking 3 hours every time I need to pull in the data.

Recall the classic 1997 quote from Jamie Zawinski:
Some people, when confronted with a problem, think "I know, I'll use regular expressions."
Now they have two problems.
Have you tried using STR_TO_DATE()? This is exactly for parsing nonstandard date/time strings into canonical datetime values.
If you try parsing with STR_TO_DATE() and the string doesn't match the expected format, the function returns NULL.
So you could try parsing in different formats, and return the first one that gives a non-null result.
UPDATE mytable
SET datecolumn = COALESCE(
STR_TO_DATE(stringcolumn, '%m/%d'),
STR_TO_DATE(stringcolumn, '%d/%m/%Y'),
...etc.
);
I can't tell what your different cases are. It might or might not be possible to cover all cases in one pass.
Another alternative is as you say, preprocess the raw data with Perl before you load it into MySQL. But even then, don't fight with regular expressions, use Date::Parse instead.

Related

Find the Number of Books in each format

I have a query to run for coursework that has to show the number of books for each format.
Here is the table I am trying to query format can be (hardback, softback, audio, ecopy)
booktable
Here is the code I have tried, I am unaware how to expand to include all format types:
SELECT format, COUNT(format) FROM book WHERE format = 'hardback' OR 'softback' OR 'audio' OR 'ecopy'
I know this is incorrect but it only shows the hardback format and how many hardback books are included.
I've decided to write an answer, because you must be wondering what happens in your query. I suppose you think it should either work or fail, but instead it works correctly for one format, but then it doesn't show any other. Why?
Your query works as follows: A where clause consists of a boolean expresssion. This can be multiple sub expressions combined with AND and OR. Your sub conditions are: format = 'hardback', 'softback', 'audio', 'ecopy'. Now, 'softback' is not really a condition. format = 'softback' would be. And here it gets weird. Rather then reporting a syntax error, MySQL wants a boolean, so it brashly converts your string.
It does so in two steps, because a string cannot be converted to boolean, but a string can be converted to number and a number to boolean. Hence the DBMS first converts your string 'softback' into a number. That should fail, but it doesn't obviously. This is the second time we expect a syntax error, but it isn't happening. MySQL takes the liberty to convert non-numeric strings into a zero.
Then MySQL converts this number into a boolean. In MySQL true = 1 and false = 0. So you have: WHERE format = 'hardback' OR false OR false OR false. Thus you only get 'hardback' books and count these. As there is just one format you select, it can be shown along with the count. I don't know whether MySQL really detects that this is valid, because the query only selects one format. I find it more likely that you are in MySQL's cheat mode (i.e. you haven't SET sql_mode = 'ONLY_FULL_GROUP_BY', which is a bad idea, because by working outside ONLY_FULL_GROUP_BY mode, you tell MySQL to let certain invalid queries pass and muddle through.) So MySQL sees there is a format to be selected, but it must be chosen which row to pick it from, and MySQL muddles through with silently applying ANY_VALUE(format).
What you want is an aggregation (count) with one result row per format. "Per ____" translates to GROUP BY ____ in SQL. So you want:
SELECT format, COUNT(*)
FROM book
GROUP BY format;
You just need to add GROUP BY format at the end of the query.
You have to write select query for each format, seperately!

Format a string with a decimal separator between every 3 digits

In a MySQL database, I have a string like 123456789. I want to add a decimal separator between every 3 digits, and thus turn it into 123.456.789.
How can I do this?
If you are using MySQL 8.0+, it is possible to use the REGEXP_REPLACE function:
SELECT REGEXP_REPLACE(YOUR_COLUMN, '([:digit:]{3})(?!$)', '$0.');
It adds a dot for each group of 3 digits, excepted for the last one.
Here are some examples:
123456789 returns 123.456.789
1234567891 returns 123.456.789.1
12345678910 returns 123.456.789.12
You can try it out on this DB Fiddle and you can change the regular expression to fit what you need.
However, this approach is probably not the best in terms of performance. If your query is called a lot of times, your database server will suffer since calculation is centralized on it. As #xNoJustice said, it is better to handle this string operation in the client part, where it will be divided between every client execution.
Use FORMAT() function with suitable locale.
fiddle, which shows all suitable locales.

questions about the datetime type values

I have several things which I want to discuss with you guys.
Since, they were just simple questions, so no dataset here.
Suppose I have a datetime type column which called started_date, the value in it was like:
yyyy-mm-dd hh:mm:ss. So, if I want to select some IDs which were larger than one specified day (let's say June/01/2017), can I just using
select ID, started_date
from table1
where started_date>"2017-06-01";
Does this work?
I tried some samples, and it worked indeed in the mysql. However, someone told me that I cannot compare the datetime column with string values without converting their format. And it confused me. Because I thought the value "2017-06-01" here was date type value, so it does not need convert. Or am I thinking wrong?
Another thing was about the double quote and single quote, I understand that the single quote was used for string values. However, in this case, when I used double quote to quote "2017-06-01", it works. So, does it mean the double quote can quote date values?
I am just asking, so any response is welcome.
Thanks.
Your query is fine. You are using a safe date/time format for the string. In other words, if you have to store the value as a string, then use that format.
I would write the code as:
where started_date >= '2017-06-01'
I see no reason to exclude midnight on 2017-06-01 (although you might have a reason). Second, single quotes are the standard delimiter for strings.
That said, you can store the value as a string.
As a best practice, I stay away from comparing time-stamps to date-stamps. In this case you can be explicit and truncate the start date. And yes, use single quotes instead.
where SUBSTR(started_date, 1, 10) > '2017-06-01'
To make sure it works you could just convert the date time to a string first and compare the two strings:
to_char(started_date,'YYYY-MM-DD') >= '2017-06-01'
The Strings will compare just fine in that format.

MYSQL REGEXP with JSON array

I have an JSON string stored in the database and I need to SQL COUNT based on the WHERE condition that is in the JSON string. I need it to work on the MYSQL 5.5.
The only solution that I found and could work is to use the REGEXP function in the SQL query.
Here is my JSON string stored in the custom_data column:
{"language_display":["1","2","3"],"quantity":1500,"meta_display:":["1","2","3"]}
https://regex101.com/r/G8gfzj/1
I now need to create a SQL sentence:
SELECT COUNT(..) WHERE custom_data REGEXP '[HELP_HERE]'
The condition that I look for is that the language_display has to be either 1, 2 or 3... or whatever value I will define when I create the SQL sentence.
So far I came here with the REGEX expression, but it does not work:
(?:\"language_display\":\[(?:"1")\])
Where 1 is replaced with the value that I look for. I could in general look also for "1" (with quotes), but it will also be found in the meta_display array, that will have different values.
I am not good with REGEX! Any suggestions?
I used the following regex to get matches on your test string
\"language_display\":\[(:?\"[0-9]\"\,)*?\"3\"(:?\,\"[0-9]\")*?\]
https://regex101.com/ is a free online regex tester, it seems to work great. Start small and work big.
Sorry it doesn't work for you. It must be failing on the non greedy '*?' perhaps try without the '?'
Have a look at how to serialize this data, with an eye to serializing the language display fields.
How to store a list in a column of a database table
Even if you were to get your idea working it will be slow as fvck. Better off to process through each row once and generate something more easily searched via sql. Even a field containing the comma separated list would be better.

SQL Where Clause with Cast or convert doesnt work

I've a table on ArcGis which contains nummbers and dates. I need to filter these via a sql-query. I just have the possibility to change the where clause.
See here: https://services3.arcgis.com/rKOPqLnqVBkPP9th/arcgis/rest/services/Arbeitsmappe1/FeatureServer/0//query
Just type in the where clause 1=1 and outfield * then you will get all results.
I have to filter installierte_leistung which contains numbers in the following formats:
1.050,20 ; 18; 0,1 ; 1.230
and dates of following format: 11.04.08
wished filters:
installierte_leistung: I want to execute a sql-statement like: where (installierte_leistung BETWEEN '1' AND '2'). In the result there is also the 18. Or if I ask for values greater 10 it shows me also the 1.050,20.
I tried to convert with cast and convert to decimal, signed, unsigned, integer and so on, but the query has been always invalid. I tried with 'number' and with number and with "number". lowercase and uppercase and almost all thinkable possibilities. I get no results with cast or convert.
Same issue with the Date. I want to filter monthly. so means between 01.2008 and 09.2009 for instance.
Could someone please help me? Thanks a lot!
Falk
I had a similar problem in the past with nested query. The more database specific queries (like cast and so) don't work because ArcGIS server is by default configured to work only with standardized queries. If you need to use more specific queries you have to change "standardizedQueries": "false" in server setting, check here how (bottom of the page): http://resources.arcgis.com/en/help/main/10.2/index.html#//015400000641000000. Should work for you. Good luck.