MySQL - Where - search string - MATCH - sql

Quick question. I'm in a bit of a rush but if someone could quickly point me in the right direction I would be very very happy.
I have a field in the db, let's call it field_a which returns a string in the format "20,50,60,80" etc.
I wish to do a query which will search in this field to see if 20 exists.
Could I use MySQL MATCH or is there a better way?
Thank you!

The better way would be to save the data differently. With WHERE a LIKE '...' and MATCH/AGAINST (besides being fairly slow) you can't easily search for just "20"... If you search for "20" you'll get "200" too; if you search for ",20," you won't get "20, 50"

Use FIND_IN_SET:
WHERE FIND_IN_SET(20, field_a) != 0

Just be careful you don't get a substring of what you actually want - for example LIKE '%20%' would also match '50,120,70'. If you're using MySQL, you might want to use REGEXP '[[:<:]]20[[:>:]]' - where the funny faces are word boundary markers that will respect break on beginning / end of string or commas so you shouldn't get any false positives.
http://dev.mysql.com/doc/refman/5.1/en/regexp.html

Related

SSRS if field value in list

I've looked through a number of tutorials and asks, and haven't found a working solution to my problem.
Suppose my dataset has two columns: sort_order and field_value. sort_order is an integer and field_value is a numerical (10,2).
I want to format some rows as #,#0 and others as #,#0.00.
Normally I would just do
iif( fields!sort_order.value = 1 or fields!sort_order.value = 23 or .....
unfortunately, the list is fairly long.
I'd like to do the equivalent of if fields!sort_order.value in (1,2,21,63,78,...) then...)
As recommended in another post, I tried the following (if sort in list, then just output a 0, else a 1. this is just to test the functionality of the IN operator):
=iif( fields!sort_order.Value IN split("1,2,3,4,5,6,8,10,11,15,16,17,18,19,20,21,26,30,31,33,34,36,37,38,41,42,44,45,46,49,50,52,53,54,57,58,59,62,63,64,67,68,70,71,75,76,77,80,81,82,92,98,99,113,115,116,120,122,123,127,130,134,136,137,143,144,146,147,148,149,154,155,156,157,162,163,164,165,170,171,172,173,183,184,185,186,192,193,194,195,201,202,203,204,210,211,212,213,263",","),0,1)
However, it doesn't look like the SSRS expression editor wants to accept the "IN" operator. Which is strange, because all the examples I've found that solve this problem use the IN operator.
Any advice?
Try using IndexOf function:
=IIF(Array.IndexOf(split("1,2,3,4,...",","),fields!sort_order.Value)>-1,0,1)
Note all values must be inside quotations.
Consider the recommendation of #Jakub, I recommend this solution if
your are feeding your report via SP and you can't touch it.
Let me know if this helps.

Regex match SQL values string with multiple rows and same number of columns

I tried to match the sql values string (0),(5),(12),... or (0,11),(122,33),(4,51),... or (0,121,12),(31,4,5),(26,227,38),... and so on with the regular expression
\(\s*\d+\s*(\s*,\s*\d+\s*)*\)(\s*,\s*\(\s*\d+\s*(\s*,\s*\d+\s*)*\))*
and it works. But...
How can I ensure that the regex does not match a values string like (0,12),(1,2,3),(56,7) with different number of columns?
Thanks in advance...
As i mentioned in comment to the question, the best way to check if input string is valid: contains the same count of numbers between brackets, is to use client side programm, but not clear SQL.
Implementation:
List<string> s = new List<string>(){
"(0),(5),(12)", "(0,11),(122,33),(4,51)",
"(0,121,12),(31,4,5),(26,227,38)","(0,12),(1,2,3),(56,7)"};
var qry = s.Select(a=>new
{
orig = a,
newst = a.Split(new string[]{"),(", "(", ")"},
StringSplitOptions.RemoveEmptyEntries)
})
.Select(a=>new
{
orig = a.orig,
isValid = (a.newst
.Sum(b=>b.Split(new char[]{','},
StringSplitOptions.RemoveEmptyEntries).Count()) %
a.newst.Count()) ==0
});
Result:
orig isValid
(0),(5),(12) True
(0,11),(122,33),(4,51) True
(0,121,12),(31,4,5),(26,227,38) True
(0,12),(1,2,3),(56,7) False
Note: The second Select statement gets the modulo of sum of comma instances and the count of items in string array returned by Split function. If the result isn't equal to zero, it means that input string is invalid.
I strongly believe there's a simplest way to achieve that, but - at this moment - i don't know how ;)
:(
Unless you add some more constraints, I don't think you can solve this problem only with regular expressions.
It isn't able to solve all of your string problems, just as it cannot be used to check that the opening and closing of brackets (like "((())()(()(())))") is invalid. That's a more complicated issue.
That's what I learnt in class :P If someone knows a way then that'd be sweet!
I'm sorry, I spent a bit of time looking into how we could turn this string into an array and do more work to it with SQL but built in functionality is lacking and the solution would end up being very hacky.
I'd recommend trying to handle this situation differently as large scale string computation isn't the best way to go if your database is to gradually fill up.
A combination of client and serverside validation can be used to help prevent bad data (like the ones with more numbers) from getting into the database.
If you need to keep those numbers then you could rework your schema to include some metadata which you can use in your queries, like how many numbers there are and whether it all matches nicely. This information can be computed inexpensively from your server and provided to the database.
Good luck!

SQL remove spaces between specific character in a string?

I want to update a database table field using another field in the same table. Currently I have this table called sources.
Name Code
In the name column I have values like this example :
' Deals On Wheels '
'Homesru - Abu Dhabi - Madinat Zayed Gold Centre'
And I am having this update statement :
UPDATE Sources
SET Code = REPLACE((LTRIM(RTRIM(Name))),' ','-')
the result is :
Deals-On-Wheels-Al-Aweer
which is fine.
but for second one I have this :
Homesru---Abu-Dhabi---Madinat-Zayed-Gold-Centre
I want it to be like this :
Homesru-Abu-Dhabi-Madinat-Zayed-Gold-Centre
How can I Achieve this ? Any Help is appreciated.
As suggested by #DanielE. my answer will point to a more global solution, in case you ever need to replace duplicated/triplicated/quadriplicated/... occurrences of a character on a string.
I'll not create a full solution for this issue, is a recurring question and there are really good solutions around already. Check these links:
SQL Server Central: remove spaces between specific character in a string?. This forum post will point to the next link I'm posting here. But is good to know what they are asking and answering.
Replace multiple spaces with new one but you can slightly modify it to replace any character you want.
You can also rely on this answer Find and remove repeated strings from Aaron Bertrand.
try
REPLACE((LTRIM(RTRIM(REPLACE((LTRIM(RTRIM(Name))),' - ','-')))),' ','-')
this will first replace ' - ' with just '-'
You might want to look into using a UDF to do a regular expression search and replace. See https://launchpad.net/mysql-udf-regexp

elastic-search on/and nesting possible?

Can and/or be nested in filters?
I want to filter something like this... a=1 AND ( d=NULL OR d>5 )
Can anyone help?
You can use a Lucene query string like this in elastic search:
http://www.elasticsearch.org/guide/reference/query-dsl/query-filter.html
and here is a reference to how you can use () for grouping ... one thing to note is the I found prefixing group statements with the + must have symbol returns more accurate results.
http://lucene.apache.org/java/3_2_0/queryparsersyntax.html
grouping is at the end.
... oh and if you going to use greater than RangeQuery can cover this case by
setting either the upper or lower term to null.
J.
This may be a bit late, but if anyone else is looking for this, I found that search word AND filters are easy to add. Just use more words in the query and separate them with space.
Scala Example:
val queryString = client.prepareSearch().setQuery(QueryBuilders.matchQuery("json.path.to.node", "sky car")).setSize(MAX_RESULTS)
val response = queryString.execute().actionGet()
Now response will have all results which containt both sky AND car

Separate key:value-string to NSDictionary

I have a string like this:
"(list:\"RTM API\" status:completed)"
And I want to convert it into a NSDictionary with the "value" before the colon as the key and the value left of the colon as the value - like this:
list: "RTM API"
status: "completed"
It can probably be done using a simple regex or so, but I don't really know how to do that.
I hope someone can explain a way to do this.
Thanks in advance.
How about this:
(\w+)\s*:\s*"([^"]+)"
Note that this won't work with keys that have spaces or special characters. Only a-zA-Z0-9 (words). Plus you ALWAYS have to have quotes around values.
This will return two sets of results, one with all keys and one with all values.
I hope this helps.