I'm using below sql query for search values from db, but when I search 'study' it will returns the values 'caese-study', 'get-study-materials' as well.
How can I use a query to search exact contains withing string column?
$names = 'study';
and the names column has values like comma separated,
Ex: 'study, abc, new' so I need to search within that too
SELECT * FROM datatitle WHERE names LIKE '%$names %' ;
SELECT * FROM datatitle WHERE names regexp '(^|[[:space:]])$names([[:space:]]|$)';
I try with above two queries but didnt work as expect, pls advice?
You should not be storing comma-separated values in a column. You should be using a junction/association table. You should fix the data model, if you can.
However, sometimes we cannot control other people's really bad decisions. MySQL has find_in_set():
SELECT dt.*
FROM datatitle dt
WHERE find_in_set(?, names) > 0;
Note that I have replaced the constant $names with a parameter. You should learn to use parameters to pass values into queries.
Related
I'm a little bit stuck.
I have an SQL column that contains weather codes (like Rain, Snow, etc.)
It is comma separated so the column would have a value of something like
rain,snow,haze
Now, I want to select the rows that contain values from an array.
I have an SQL code that is something like this:
SELECT * FROM locations WHERE currentWeather IN ('rain', 'snow', 'cloudy') ORDER BY name ASC
The problem is that this obviously works when currentWeather column only contains one item.
Is there a way to do it so that if the column value contains any of the items from the given array, it selects it?
Also, would it select it twice if two items match?
Best wishes
Use unnest in a subselect.
Select distinct A.myArray from (select unnest(column) as myArray from table) A where A.myArray in (your words to filter for)
Notice that using arrays in sql isn't very ideal and does not follows normalization rules. Your tables should ideally not contain arrays but rather just several rows each one containing the specific value you Want. It prevents issues such as this one.
To avoid the selection of repeated values, use the Distinct keyword right after you write select.
Rsference:
https://www.w3resource.com/PostgreSQL/postgresql_unnest-function.php
WHERE FIND_IN_SET(currentWeather, "rain,snow,cloudy")
Picks apart the string at commas (only) to see if currentWeather is any one of those 3 'words'.
See also FIELD(...)
Am using a SQL command in PHP to count the no of values inserted in a column named attack_type. I want to count the occurrence of individual values like website defacement in the whole column of the table. But here the column attack_type contain different values, separated by a comma and the count is treating whole column data as a string. Below is my current SQL statement with its output
I tried explode print_r in PHP
SELECT attack_type,
count(*) as number
FROM data_input_test
GROUP BY attack_type
Here is the output of the above statement
generated:
https://drive.google.com/open?id=1TyRL_Mh0OOJWaCpFczxmBr34No9LUpzH
But what I want is :
https://drive.google.com/open?id=1eeA_1TCER0WMpZwSkBDMzRtRa8xihbZd
and so on. The above desired output is edited to show what I exactly want.
Other answer on stackoverflow and on other forums are either irrelevant or are using regrex or a new table creation in one or the other way. That I don't want as my hosting has some limitations. My hosting doesnt provide creation of triggers, regrex or creation of temp tables
I may have a solution for this but don't know how to apply here. Possible here: https://www.periscopedata.com/blog/splitting-comma-separated-values-in-mysql
Please someone explain me how to apply the same here.
So I finally worked around to get my work done using the select only. This only works if you have a finite set of data or specifically less than 64 values.
Change your column datatype to 'set' type. And enter your set values.
Now use select, count, find_in_set and union functions of sql.
Example:
union select 'Un-patched Vulnerable Software Exploitaion'as type, count(*) as number from data_input_test where find_in_set('Un-patched Vulnerable Software Exploitaion',attack_type)```
and so on for all your values
I know this is not how you should do but as the legends say this works 😎😎
If you just want to count comma-separated values in rows, you can use:
SELECT SUM(LENGTH(attack_type) - LENGTH(replace(attack_type, ',', '')) +1) AS TotalCount
FROM table_name;
I have created a table in MySQL in which a "skill" field has multiple comma-separated values, for instance: "PHP, JavaScript, C#".
I want to know an SQL query which will go through all values and give back a result according to the search values.
The correct MySQL function is FIND_IN_SET().
You would use it like:
SELECT * FROM USERS WHERE FIND_IN_SET('PHP', skill)>0
Where you can swap PHP out for the string you are searching for. This isn't the most efficient way to organize this data, but for smaller data sets might be fine.
I am having an issue where I have a table in a database which stores values in this form 1,3,4,55,6,22,44 and I have an array which is dynamic from the client side it can be like 2,55,33,1,33,99
I want to make a query to select this field if the at least any value matches between the fields.
Like select the field if in the database value there exists 24 and I have 23,24,55,66 from the user array
I think this can be done with find_in_set() or the IN keyword
It is not a good practice to create comma seperated values in a column. Usually people feel that it was the easiest and simplest method, but it is not. Searching and modification will be so hard. Find set can be used if you have a single item to search ; In your case you can do it like this. Implode the array with | and use it in regular expression.
<?php
$arr = Array(2,55,33,1,33,99);
echo 'select * from table where CONCAT(",", `field`, ",") REGEXP ",('.implode("|",$arr).'),"';
?>
For comparing two arrays, you should use:
array_intersect()
after converting table data into array as well.
Reference
I have 100K datas in my mysql database, I want to search a query in it. I removed stop-words and splitted it into an array of keywords and stored in a variable ie $key[0],$key[1],$key[2].I am using the following query
SELECT *
FROM `table`
WHERE (`column` LIKE '%$key1%'
OR `column` LIKE '%$key2%'
OR `column` LIKE '%$key3%');
is any other faster ways to do the same.
The only way to speed up queries like this is to use full-text searching. LIKE '%string%' can't be optimized with normal indexes, because they use B-trees that depend on matching the prefix of the string being searched for. Since your pattern begins with a wildcard, the index doesn't help.
Another solution is to normalize your database. Don't put the keywords all in one column, put them in another table, with a foreign key to this table and a row for each FK+keyword. Then you can use a join to match the keywords.
Also, you're using the wrong type of quotes around your column names. They should be backticks, not single quotes.
you can do something like this
SELECT *
FROM table
WHERE colomn REGEXP '$key1|$key2|$key3'
etc etc so instead of creating your array as a comma separated list of key words do it as a pipe separated list and then just push the string into your regex too this is simply an example
Don't SELECT *, only select what you need.
If you want to do complete-text searches, lose the % and add an index
You misspelled column