I have a table on MySQL, called Items with 2 columns: Id and Name. I want to show my items, filtering by its name first character. To do this, now I'm using this query:
Select Id,Name from Items WHERE Name LIKE 'a%'
I have 2 questions:
1) It is this the best method to achieve that?
2) To create the filter view, I want to know which characters have at least one item name starting with it. For example, I don't have any item name starting with "X". How could I know which ones have with a single query?
Thanks
If you have an Index on Name then your query is fine.
To get all characters having Names
Select substr(Name, 1, 1) as starting_character
from Items
group by starting_character
order by starting_character
You could run a large OR query like....
select * from Items where nobre like "A%" or nombre like "B%" or nombre like "C%" //etc etc
But if speed and table size is an issue, I would create another column, and just enter the letter value as an INT into that column. Kinda like an index.
So when you insert any new values, just code up a function to return the letter value of the first letter, and insert that into the new column.
Now you can query the column for any letter, based on that integer.
Hope that came out clearly, Im not very good at explaining things sometimes.....
This will give you all the first characters - only once (hence the DISTINCT)
SELECT DISTINCT SUBSTR(Name,1,1) FROM Items ORDER BY SUBSTR(Name,1,1)
Then you can use this to create your filters.
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(...)
I got table promos, with field store_id_list (VARCHAR). what i want to achieve here is i want this promo can be available into multiple store in 1 record, instead using multiple record, the store_id_list value is the list of store_id separated by comma (ex: 1,4,5,7,)
Now, i want to get record of table promo, where i have single store_id value, ex: store_id=5 how can i do that in MySQL? can i do that in single query? if using LIKE then more likely i can get 15 or 45 instead of 5.
My advice is to normalize your tables, and have a db-record per store/promo. But it can be done like this:
Make sure you have commas at the beginning and end of the column value, like this:
store_id_list : ,1,4,5,7,
And then query like this:
... where store_id_list like '%,5,%'
I think you are looking for FIND_IN_SET function. For example:
SELECT * FROM tbl WHERE FIND_IN_SET('5', store_id) > 0;
I am having a table with a column that has few ids that were put into database with multi select. Column for example contains: 1,4,5,7,9. Is it possible to check if this column contains for example number 5 or not in it through MySQL query ?.
I need to select all the people that have number 5 or some other listed in that field and print them through php.
http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_find-in-set
SELECT ...
WHERE FIND_IN_SET(5, list_column)
But understand that this search is bound to be very slow. It cannot use an index, and it will cause a full table-scan (reading every row in the table). As the table grows, the query will become unusably slow.
Please read my answer to Is storing a delimited list in a database column really that bad?
You can use #MikeChristensen's answer to be more standard. Another trick with standard SQL is this:
select * from TableName
where ',' || ids || ',' LIKE '%,5,%'
(in standard SQL, || is the string concatenation operator, but in MySQL, you have to SET SQL_MODE=PIPES_AS_CONCAT or SET SQL_MODE=ANSI to get that behavior.)
Another MySQL-specific solution is to use a special word-boundary regular expression, which will match either the comma punctuation or beginning/end of string:
select * from TableName
where ids RLIKE '[[:<:]]5[[:>:]]'
None of these solutions scale well; they all cause table-scans. Sorry I understand you cannot change the database design, but if your project next requires to make the query faster, you can tell them it's not possible without redesigning the table.
Perhaps:
select * from TableName
where ids = '5' -- only 5
or ids like '5,%' -- begins with 5
or ids like '%,5' -- ends with 5
or ids like '%,5,%' -- 5 in the middle somewhere
It probably won't be very fast on large amounts of data. I'd suggest normalizing these multi-selection values into a new table, where each selection is a single row with a link to TableName.
select * from your_table where concat(',',target_column,',') like '%,5,%'
you can write the sql query like this, for example you are looking for the number 5
select * from your_table_name where ids='5'
if you want to check the result with php just tell me i will write it for you :)
I have an application with images stored in multiple categories, currently being stored by category ID in a column as a space separated list (eg. 1 5 23 2).
I have a query from a search filter, which is currently an array of IDs, (eg. 1 5).
Ideally, I'd find a solution using something like WHERE IN that would see if any of my array values exist in the stored column, although I don't see an easy solution.
At the moment I have to query all the images, bring them into PHP and check there, using "array_intersect". I see this as being a problem if I have 100,000s of images in the future to pull and then check.
Can anyone think of an elegant solution? The application is still in development, so I could arguably change the structure of my tables.
I think adding a map table would probably be best here which maps the image_id with the category_id.
refactor your database tables!!!
use sth like this:
table_image
id int
name text,
content text,
...
and a second table for the categories:
table_category
id int,
image_id int,
category int
this way, you can store categories in a separate table using foreign keys. now, you can do simple sql queries like
SELECT table_image.id FROM table_image, table_category WHERE table_image.id = table_category.image_id and table_category.category = $cat_arr[0] OR table_category.category = $cat_arr[1] ...
H Hatfield has the best answer. If you really must use a single column (which I do not recommend) you could store the categories as a comma separated list instead of spaces. You can then use the MySql function find_in_set, as such:
WHERE FIND_IN_SET('3', categoryListColumnName) > 0 OR FIND_IN_SET('15', categoryListColumnName) > 0
Using your current database design you could use an IN query:
WHERE categoryListColumnName LIKE '% 3 %' OR categoryListColumnName LIKE '% 15 %'
and add more OR's for every category you want to find. When using this query you have to make sure your list separated by spaces ends and starts with a space, otherwise it won't work.
Let me just reiterate, that these methods will work, but they are not recommended.
I want to filter result of my SQL query. I want to select everything that has some specific text in some column.
Example:
SELECT * FROM categories WHERE (name
has 'abc' values in it's value ex.
MyabcCategory)
Also maybe it is not very good idea to do that in query, maybe it is better to get all and then filter array instead? But I don't know how to do that aether.
Use LIKE with % wildcard:
SELECT * FROM categories WHERE name LIKE '%abc%'
This will give you all the records that have abc somewhere in them.
You can learn more about it here :)
You want to use the LIKE operator, with % to match any character before and after your specific word :
select *
from categories
where name like '%abc%';
But note that doing so, MySQL will scan each line of the table, every time the query is executed... which might not be great if you have a lot of data.
If you're searching for some kind of text, you might either want to :
Use a FULLTEXT index, if you're working with MyISAM tables.
Or, use a solution that's separated from MySQL, with a specific indexing/search engine, such as Solr.
SELECT * FROM categories WHERE name LIKE '%abc%'