MySQL UNION SELECT until found? - php

Let's say I have table with column 'URL' whrere I store urls like this
one/two
one/two/three
alpha/omega
And I want to get data from database for specific url and if it is not found I remove the last part of url and search again:
Example:
I have url like one/two/three/four/five.
I do search for "one/two/three/four/five"
if not found search again for "one/two/three/four"
if not found search again for "one/two/three"
if not found search again for "one/two"
I would like to have something like:
SELECT * FROM db WHERE url=one/two/three/four/five
UNION
SELECT * FROM db WHERE url=one/two/three/four/five
UNION
SELECT * FROM db WHERE url=one/two/three/four
UNION
SELECT * FROM db WHERE url=one/two/three
UNION
SELECT * FROM db WHERE url=one/two
UNION
SELECT * FROM db WHERE url=one
but I want to stop searching if the row is found.
Is this possible or do I have to do it with separated queries.
Thanks for help.

I thing that this is the most elegant approach to your question. This statement is independent depth path and you don't need to split constant url in subsequent selects:
SELECT
*
FROM
db
WHERE
concat( 'one/two/three/four/five' , '/') like concat( url , '/%')
ORDER BY
LENGTH (url) desc
LIMIT 1
I have tested this query in MySQL, also you can check it! (in MSSQL syntax)

Just replace UNION with UNION ALL and add LIMIT 1 at the end.
P.S. UNION ALL would not make much difference in this particular example, but it is useful to know the difference: http://www.mysqlperformanceblog.com/2007/10/05/union-vs-union-all-performance/

Let's say I have table with column 'URL' whrere I store urls like this
one/two
one/two/three
alpha/omega
Don't do that, it's a horrible design and the proof is the problem you are having running such a simple query; store each URl on a DIFFERENT ROW. Read up on Normalization.

You could use a regexp to search in a single query, but it'll get you all rows:
SELECT * FROM db WHERE url REGEXP "^one((/two)|(/two/three)|(two/three/four)|(/two/three/four/five))?$"
so if you only want the results from the first WHERE you'll have to do multiple queries.
If you really want to have a single query and don't care about a little overhead in the search you could do
SELECT * FROM db WHERE url REGEXP "^one((/two)|(/two/three)|(two/three/four)|(/two/three/four/five))?$" ORDER BY length(url) DESC LIMIT 1
This will get you the first possible result only, but the query inside will have to get all possible results first -> less efficient, but more compact.
I hope this helps!

Related

mysql find_in_set string starting with

I need to search value starting with given string in comma separated values.
Example,
I have '1_2_3_4_5_6, 1_2_3_4_5_8, 1_2_3_6_5_8' in my column. I can search for rows with exact value using
select * from table where find_in_set('1_2_3_4_5_6',column)
But how to search, if starting part of the string is given? something like this:
select * from table where find_in_set('1_2_3%',column) ?
If I understand you correctly (I'm still not sure I do), you could just use:
SELECT * FROM table WHERE column LIKE '%1_2_3%';
This would give you columns where the value is like:
1_2_3_4_5_5
1_4_5_, 1_2_3_4_5_, 6_7
and so on.
But you should really normalize your tables. This is important for good queries and performance wise also important.
According to #Xatenev suggestions, if you really like only the values and the row of each matching row, this won't work so well and will be a lot of overhead. This are the steps that I would perform:
Split all CSV columns into multiple rows (this is a hack and a performance killer, I found some working solution but did not test it, see here): Pseudo Code: SELECT ID, SPLIT(',', column) AS entries FROM table (NOT WORKING)
Filter the new virtual table to select only rows that match the prefix (SELECT * FROM virtual_table WHERE find_in_set("1_2_3%, entries) ORDER BY ID)
Concatenate the matching entries back into a list for each ID. e.g. SELECT ID, GROUP_CONCAT(entries SEPARATOR ', ') FROM filtered_table GROUP BY ID
Do something
The unknown part is the beginning with the split in multiple rows. There are a lot of possible solutions all with their own drawbacks or advantages. Be aware that this will always (regardless of the selected method) will cost a lot of performance.
ADDITIONAL NODE:
It could be adventures in your situation, that you get each row matching your search string like in my first example and filter them in memory. This might be faster than doing this in MYSQL.
you can try with 'REGEXP'
If you want to match data with subtring, please try this
SELECT * FROM `table` WHERE `column` REGEXP '[, ]?1_2_3[^,]*,?' ;
Or
If you want to exact start match, please try this
SELECT * FROM `table` WHERE `column` REGEXP '[, ]?1_2_3[^,]*,?' AND `column` NOT REGEXP '[^, ]1_2_3[^,]*,?' ;
I was able to solve it with no-regex. Sonam's Answer is correct as well.
SELECT * from table WHERE CONCAT(',', columnname, ',') like '%,1_2_3%'

Get an array of all columns starting with the same characters.

This is quite difficult to explain in the title, so I'll do my best here. Basically I have a column in a MySQL products table that contains rows like:
FEL10
FEL20
FEL30
PRO05
PRO07
PRO08
VAI12
VAI13
VAI14
These are the categories ("FEL","PRO","VAI") and a identification number of my products ("10", "20" and so on). I need an SQL select query that creates me a textual array like:
FEL*
PRO*
VAI*
With this array I need to create a listbox, that allows me to choose a category (regardless of the identification number). Once I choose a category, let's say PRO*, I will need to do the reverse action: print all the products info related to PRO05, PRO07 and PRO08.
How do you think you can achieve this? I have been trying using the DISTINCT statement but I need to filter only the first characters, otherwise it will be useless. I also tried the SUBSTRING() and LEFT() functions, but they seem not to be working (I get an SQL Syntax error).
--
Thanks for your help as always
What is wrong with?
SELECT distinct left(col, 3) as category FROM `table1`
MySQL LIKE to the resque:
SELECT col1 FROM table1 WHERE col1 LIKE 'FEL%';
This way you have to add all cases using OR.
Alternative - REGEXP:
SELECT col1 FROM table1 WHERE col1 REGEXP '(FEL|PRO|VAI).*'
Then it's just a matter of writing proper regex.
I would use extra col to group your items - to avoid such selecting altogether (which should be quite expensive on bigger dataset).
https://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp
To get the list of the 3-letter codes use:
select distinct left(combicode, 3)
from mytable;
When a user selects one of the values use this to get all matching entries:
select *
from mytable
where combicode like concat(#category, '%');
(Aside from that: It's a bad idea to have concatenated values in one column. Why not have one column for the category and another for the product code? Then there would be no problem at all.)

This query on mysql is taking forever to execute

im making a simple admin module to query the database to show the results. Im using this query via php:
SELECT
*
FROM myTable
WHERE id in(SELECT
id_registro
FROM myOtherTable
where id_forma='".$id_club."' and fecha_visita Like '%".$hoy."%'
)
order by id DESC
The result shows, however, it takes very long like 2 minutes..Anyone can help me out?
Thanks!
Without seeing your database, it is hard to find a way to make it faster.
Maybe you can try to turn your WHERE IN to INNER JOIN. To something like this
SELECT * FROM myTable INNER JOIN myOtherTable
ON (myTable.id = myOtherTable.id_registro)
WHERE myOtherTable.id_forma = '$id_club'
AND myOtherTable.fecha_visita LIKE '%$hoy%'
ORDER BY myTable.id DESC
Noted that you should sanitize your variable before putting it SQL query or using PDO prepare statement.
Sub Queries takes always time, so its better to ignore them as much as possible.
Try to optimize your query by checking its cardinality,possible keys getting implemented by DESC or EXPLAIN , and if necessary use FORCE INDEX over possible keys.
and I guess you can modify your query as:
SELECT
*
FROM myTable
inner join id_registro
on (id = id_forma )
where
id_forma='".$id_club."' and fecha_visita Like '%".$hoy."%'
order by id DESC
LIKE in mysql may take a long time ,with or without index.
Do u have a very large DB?

Mysql Select String Function Problem

I want to select records in my table when it matches a row that ends with a particular value.
eg.
if 'oop' is found at the end of a particular record it select the record
Pls how can i go about it
thanks
You can use LIKE:
SELECT *
FROM your_table
WHERE your_column LIKE '%oop'
Note that this query will result in a full scan so it might be slow if you have many rows.
select * from yourtable where somevalue like '%oop'
SELECT *
FROM your_table
WHERE your_column REGEXP 'oop'
Regular Expression Queries can open up some pretty cool extra features that like can't touch.

Mysql Unique Query

I have a programme listing database with all the information needed for one programme packed into one table (I should have split programmes and episodes into their own) Now since there are multiple episodes for any given show I wish to display the main page with just the title names in ascending and chosen letter. Now I know how to do the basic query but this is all i know
SELECT DISTINCT title FROM programme_table WHERE title LIKE '$letter%'
I know that works i use it. But I am using a dynamic image loading that requires a series number to return that image full so how do I get the title to be distinct but also load the series number from that title?
I hope I have been clear.
Thanks for any help
Paul
You can substitute the DISTINCT keyword for a GROUP BY clause.
SELECT
title
, series_number
FROM
programme_table
WHERE title LIKE '$letter%'
GROUP BY
title
, series_number
There are currently two other valid options:
The option suggested by Mohammad is to use a HAVING clause in stead of the WHERE clause this is actually less optimal:
The WHERE clause is used to restrict records, and is also used by the query optimizer to determine which indexes and tables to use. HAVING is a "filter" on the final result set, and is applied after ORDER BY and GROUP BY, so MySQL cannot use it to optimize the query.
So HAVING is a lot less optimal and you should only use it when you cannot use 'WHERE' to get your results.
quosoo points out that the DISTINCT keyword is valid for all listed columns in the query. This is true, but generally people do not recommend it (there is no performance difference *In some specific cases there is a performance difference***)**. The MySQL optimizer however spits out the same query for both so there is no actual performance difference.
Update
Although MySQL does apply the same optimization to both queries, there is actually a difference: when DISTINCT is used in combination with a LIMIT clause, MySQL stops as soon as it finds enough unique rows. so
SELECT DISTINCT
title
, series_number
FROM
programme_table
WHERE
title LIKE '$letter%'
is actually the best option.
select title,series_number from programme_table group by title,series_number having title like '$letter%';
DISTINCT keyword works actually for a list of colums so if you just add the series to your query it should return a set of unique title, series combinations:
SELECT DISTINCT title, series FROM programme_table WHERE title LIKE '$letter%'
Hey thanks for that but i have about 1000 entries with the same series so it would single out the series as well rendering about 999 programmes useless and donot show.
I however found out away to make it unique and show the series number
SELECT * FROM four a INNER JOIN (SELECT title, MIN(series) AS MinPid FROM four WHERE title LIKE '$letter%' GROUP BY title) b ON a.title = b.title AND a.series = b.MinPid
Hopefully it helps anyone in the future and thank you for the replies :)

Categories