Is it possible to write a function within mySQL that checks the value of a SELECT query, and if it != 0, continue running the function and add to the result array?
I have a few entries marked as related_id = 0 The rest have actual positive numbers attached.
I am trying to create a single query that will continually loop through a sql function, check and see if the retrieved related_id result is 0. If not, then it will run again, add the newly checked row to the result array and continue until it finds a 0.
The way the DB is set up, a 0 will always occur, and it will be searching via id,so there should only be one result.
I am using a slightly modified tagging system.
keywords_id | keyword | related_id
------------------------------------
1 | sports | 0
2 | baseball | 1
3 | football | 1
4 | pitchers | 2
If I pass in related_id = 2 I’m looking to return an array that yields:
array
[0]
keyword => 'sports'
keywords_id => '1'
related_id => '0'
[1]
keyword => 'baseball'
keywords_id => '2'
related_id => '1'
[2]
keyword => 'pitcher'
keywords_id => '4'
related_id => '2'
I tried my luck with using IF and THEN but i just haven’t seen enough examples and its tough to find solid tutorials online. Thanks!
SELECT k.*
FROM keywords k
WHERE keywords_id = 2
The above query would essentially start it off. The keywords_id is the related_id that is passed. Therefore the above would return keywords_id: 2 |keyword: baseball |related_id: 1
Because related_id 1 is NOT 0, i would need to run it again.
I realize this can be done in PHP through a few extra queries…is that the way I should do this? I assume it could be done in mySQL after reading about functions. I just couldn’t figure it out.
MySQL doesn’t support returning an array from a function. Would suggest creating a table (or possibly a temporary table) to hold the results and then writing a stored procedure to populate it instead.
Not sure exactly what you are trying to achieve but maybe something along the lines of this?
See SQL Fiddle Demo