Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    MYSQL




Recursive Function In Mysql ?


My table
--------

id -- value -- ref_id
----------------------
1--rqwer-0
2--23ew-1
3--23ewe-2
4--123ff-1
5--de123-4

Now i want to take the values like id and refer has to be same and one more condition ,
i need the output as

1,2,4,5

How can i get ?




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Does Mysql Support Recursive Queries?
Does mysql support recursive queries?

Recursive
I have a table called places with 3 fields,
ID, parentID, and Desc.
1, 0, Europe
2, 1, Spain
3, 1, Monaco
4, 2, Andalucia
5, 4, Malaga

I would like to be able to display all the data in a tree:
Europe, Spain, Andalucia, Malaga
Europe, Monaco

The problem is that not all branches are the same size.
I have seen examples that allow me to find all the children of a record, and the parents of a record, using self joins. But I can't figure out how to find grandchildren, etc. Is this even possible?

Recursive Functions
Can you create recursive functions or stored procedures?
I did make a simple stored procedure. But once the recursive querry was called,
I got:
ERROR 1424 (HY000): Recursive stored routines are not allowed.

Recursive Select
I'm wondering if given this table structure:Code:

| id | parent | name |
| 1 | NULL | x |
| 2 | NULL | y |
| 3 | 1 | z |
| 4 | 3 | q |
| 5 | 3 | e |
| 6 | 5 | r |

Is it possible to run a query which given any ID will be able to find the parents of that record as well as that parent's parents and that parent's parents and so on? IE, run the query on the id=6 and we'd get ids 5,3,1. Run it on id = 4 and we'd get 3,1.

Conversely can we do a similar query that would find all the children and the children's children of a given record? so id=1 woul return 3,4,5,6. id=2 would return nothing, id=3 would return 4,5,6

Selecting Recursive Rows
computers(id_computer,description,id_location);
locations(id_location,description,father);

I have this two tables: computers and locations;
In locations I can insert a location and tell which one is his father, so I can have locations inside of locations.

------------------------------------------------
id_location, description, father
------------------------------------------------
1, Main Building, 0
2, HRs, 1
3, Director, 2
4, Warehouse, 0
5, Office, 4
6, Director, 5
-------------------------------------------

When I insert a new computer, I tell in which location is that computer

-------------------------------------------------------
id_computer, description, id_location
-------------------------------------------------------
1, Fujitsu-Siemens 4200, 2
2, Fujitsu-Siemens 5300, 3
3, Fujitsu-Siemens 4200, 5
4, Fujitsu-Siemens 5300, 6
------------------------------------------------

Now I would like to select all computers from main building for example.

I can not select * from computers where id_location=1 because that would not get the computers from HRs and Director. I would like to have all computers listed.

Creating Recursive Variables And Analysing
This query has an error in the "where" stance. Apart from that, i want to create recursive vars in the query, for example :

Adding another var using "as" that does:
valor_dinamico + 1000 as valor_plus .

and the sum of those, for example:
valor_dinamico + valor_plus as valor_sum

SELECT
ventas.*, ventas.importe_acordado - SUM(pagos.importe) as valor_dinamico

FROM ventas

LEFT OUTER JOIN pagos ON pagos.venta = ventas.id
Where valor_dinamico > 0
GROUP BY ventas.id

is there anyway to do that ?

Mysql_affected_rows And Recursive Cascading Deletes Possible
I have 5.1.17 and one table 'connected' to itself via a foreign key (see below)
When I delete a parent post with children they all get deleted BUT a subsequent call to mysql_affected_rows always returns 1.

I would expect/hope that it returns the total number of deleted posts(including any cascading ones) Am I wrong??

IF Function,GROUP BY,aggregate Function Problems
Yep, I have all those problems in the title. So I'll explain each one at a time - I did have another thread relating to this very same query but I thought it was time to update where I am with the query because at the moment I feel like I am getting nowhere!

The query I have basically searches through an items_ordered table through each product and checks to see whether the item is VATable or not. This is not where I have the problem though. Where I am really having the first problem is when I am trying to use the IF function to check if the TOTAL of an order is over £300. IF it is then I multiply it my 0.95 (i.e. 5% off). With the query below I get no errors but neither do I get the desired result. It's as though it couldn't even see it. =....

"Recursive" Query Issue
I'm having problems creating a query. The table I want to query has three columns - unique ID (auto_increment), parent row ID and a data row.

I want MySQL to return all the rows which have ID x (defined in the query), and check its parent ID and return the row with the same ID than the previous row had as parent ID. And this should continue until parent is 0, when it would stop.

Is this possible in MySQL (I'm using MySQL 5) and how can it be done? I have tested using variables with no success.

Mysql Function
i am hosting my website on a hosting website server.  I made Mysql database there. I noticed one thing when i insert data in tables they have a colum called "function" with drop down box where they have values like ASCII,CHAR,SOUNDEX, UCASE, LCASE, COUNT,AVG any many other.

I don't pick any of them. But I am just wondering if I need to pick either ASCII or char?

MYSQL Function For 'or'?
In the context of a where statement, what is the correct way to say 'or' as in the following:

SELECT * FROM table WHERE field1 [or] field 2 LIKE "%$query%"

This is for a basic search feature where people are tending to misspell words, I'd like to add a search words column that will also be searched.

Mysql 4 Function From A Mysql 5 Function
I found this function on the mysql website :

CREATE FUNCTION substrCount(x TEXT, delim varchar(100)) RETURNS int
RETURN (length(x) - length(REPLACE(x, delim, ''))) / length(delim);

That works perfectly with mysql 5. But when I try to import this to mysql 4, I have an error :

suse-server:/partages # mysql mybase <function-add.sql> output.tab
ERROR 1064 (42000) at line 1: You have an error IN your SQL syntax; CHECK the manual that corresponds TO your MySQL server version FOR the RIGHT syntax TO USE near '(x TEXT, delim varchar(100)) returns int
return (length(x)-length(REPLACE(x, del' at line 1

Mysql Function
is there any function in mysql which tells you what the last row inserted into a table is?

Function In MYSQL
I am using MYSQL 5.0.22. My database name is 'normal'. It could contain 2 tables, such as Itemgroup & Itemlist. I tried with the FUNCTION query for Concatination purpose. Funtion name is Serial, The Query is,
CREATE FUNCTION Serial (s CHAR(10)) RETURNS CHAR(25) RETURN CONCAT('SALES',s,'IND');
It would say the error as followes,
ERROR 1044 (42000): Access denied for user 'root'@'%' to database 'normal'
Is the Query right or wrong? or How will I used (or) handiled the FUNCTION option?
If any one knows, please guid me

Warning: Mysql() [function.mysql]: Access Denied For User 'apache'@'localhost' (using
my script is not connecting to my database, i get this error

Warning: mysql() [function.mysql]: Access denied for user 'apache'@'localhost' (using password: NO)

Mysql IF Function Question
I am trying to incorporate an IF statement into a query so that it will show a P after a phone number if this phone is a personal cell phone. This is being used in a view that I use in multiple locations to create phone listings of all employees in the directory.
My query is:

CREATE VIEW phonelisting as select
users.UserID,
concat_ws(' ', users.fname, users.minitial, users.lname) userName,
users.positionTitle AS positionTitle,
group_concat(distinct concat('(', substr(CAST(did.DIDID as CHAR), 1, 3), ') ', substr(CAST(did.DIDID as CHAR), 4, 3), '-', substr(CAST(did.DIDID as CHAR),7 , 4)) order by CAST(did.DIDID as CHAR) ASC separator '<br />') dids,
group_concat(DISTINCT CAST(phone.ExtensionID as CHAR) ORDER BY CAST(phone.ExtensionID as CHAR) ASC SEPARATOR '<br />') extensions,
users.homePhone,
users.pager,
group_concat(distinct concat('(', substr(cell.number, 1, 3), ') ', substr(cell.number, 4, 3), '-', substr(cell.number,7 , 4)) order by cell.number ASC separator '<br />') AS cellphones
FROM
users
LEFT JOIN
cellrelationship
ON
cellrelationship.userID = users.UserID
LEFT JOIN
cell
ON
cell.CellID = cellrelationship.cellID AND cell.hideListing <> &#391;'
LEFT OUTER JOIN
phonerelationship
ON
users.UserID = phonerelationship.UserID
LEFT OUTER JOIN
phone
ON
phone.PhoneID = phonerelationship.PhoneID
LEFT OUTER JOIN
DID
ON
did.ExtensionID = phone.ExtensionID
WHERE
users.userStatus <> 'term'
AND
users.hideListing <> &#391;'
AND
(users.termdate = '' OR users.termdate >= UNIX_TIMESTAMP(CURRENT_DATE))
AND
users.hireDate <= UNIX_TIMESTAMP(CURRENT_DATE)
GROUP BY
users.UserID
ORDER BY
userName
I would like to have the P show up at the end of each phone listed(Only if it is a personal phone) on the line with:


group_concat(distinct concat('(', substr(cell.number, 1, 3), ') ', substr(cell.number, 4, 3), '-', substr(cell.number,7 , 4)) order by cell.number ASC separator '<br />') AS cellphones
The way I determine if it is a personal cell or company cell is by the value of cell.Type being Company or personal.

Any suggestions?

*I am running mysql 5.0.27

Mysql Date Function
I just want to know if this command below is acceptable in MySQL form? Because, I have made a web form processing in which the date is basing as EST time (east standard time in US) and I'm in ASIA. I just found a mysql function date thru googling..

$sql = "INSERT INTO table SET
date = SUBDATE(NOW(), INTERVAL 1 DAY)";

MySQL Have A Decode Function??
Oracle has Decode(asdf,asdf,adf,adf) etc.

does MySQL have an equivilant?

UNION Function How To In MySQL 3
How to write this line in mysql3 where there is no UNION function?

(SELECT * FROM table1) UNION (SELECT * FROM table1) ORDER BY date LIMIT 0,5;

Is There Trigger Function In MySQL ?
It seems to me that there is no trigger function in MySQL but I am =
not sure.

Recently, I have a project which need the trigger function when MySQL =
database server receive a alert information and wake up some procedure. =
Is there any other method to do the same functionality of trigger as in =
ORACLE databse ?

MySQL Now() Function Problem
I am new to MySQL and my problem is with storing a datetime value in a
table. I created a table with a column designated as DATETIME. I
fill it with the NOW() function. No matter whether I default it or
try and set with code, all I get is a date! Even running "SELECT
Now()" only returns a date.

If I run the following query:

Date_Format(now(), GET_FORMAT(DATETIME,'USA'))

it returns a datetime value. However, if I use that SAME query to try
and fill the column during insert, I still get only a date value.

I've even tried some date calculations like Now() + 0 but still get
ONLY a date, no time info.

ENCRYPT Function In Mysql
My password column is encrypted using ENCRYPT() function. When I execute the following query in phpmyadmin, it is showing 0 records. Because everytime, encrypt function is executed, it is returning new value. But my squirrelmail application is decrypting the password correctly.

$query="SELECT * FROM users WHERE email = 'xxx@xxx.com' and password=ENCRYPT('smart')";

how to check whether the user entered password is correct as in mysql?

Mysql Stored Function ...
I'm new to creating stored procedure - can someone tell me where i've gone wrong here - the below code refuses to execute. Essentially, all i want do it something like;

INSERT INTO sometable(a,b,c) VALUE(12,'12',itypes('information'));

if the category 'information' doesn't exist in the event_types table, it's create and the id return - else just returns the id

CREATE FUNCTION .`itypes` ( _tname VARCHAR(45))
RETURNS INT
BEGIN
DECLARE tmp INT;
SELECT id INTO tmp FROM event_types WHERE tname LIKE _tname;
IF (id IS NULL) THEN INSERT INTO event_types ( tname ) VALUES ( _tname );
END IF;
SELECT id INTO tmp FROM event_types WHERE tname LIKE _tname;
RETURN tmp
END

Init_cap() Function In MYSQL
Is there any string function available to get the First Character alone with upper case in MYSQL5.0

For Ex:
remma.

Output:
Remma

Push/pop Function For MySQL
if MySQL has a push/pop function? I'm creating a table for news items, with three rows - one for the date, one for the title, and one for the URL. What I want to do is limit the number of news items held in the table to 10. For example, if there are 10 entries in the table already (date/title/url sets) and I add another item, I want to put it at the top of the table and pop the bottom value off the table.

I know I can do this by exporting the table to an array in PHP, then messing with it there and writing it back to the table, but this would take a lot of MySQL queries I think.

Is there an easy solution to this problem I'm not seeing?

MySQL IF() Function Problem
I want to select 2 dates from a database (fields called start_date and end_date). However, I want to in some way make the returned value of end_date equal to that of start_date if end_date is null.
I've tried using the if() function as follows:

$result = mysql_query("select start_date, if(end_date is null, start_date) from events");

Where events is my table name. This doesn't work. I've tried it with quotes around start_date in the if but that just returns the word start_date.


Variable Function In MySQL
Is there a way to use a 'variable function' in MySQL, e.g.Code:

SELECT @hash:= value FROM prefs WHERE key = 'hash_method';
-- @hash = SHA1
SELECT @hash('test string');

So the variable @hash stores the current hash method in the `prefs` table.
This method does not work, is there a way to do this?

An IMPLODE() Type Function For MySQL??
I'm looking to pull data (just one column) from mysql which is over multiple rows.

e.g.

apple
banana
orange
pear

Now, I actually want the data in this format in just one row:

"apple,banana,orange,pear"

Does mysql offer some sort of "SELECT IMPLODE(',', my_column) AS foo" type of thing? I know I can do it with PHP but this a part of a much larger query so I'm trying to keep this all in a single query.

Is There An 'Is Negative' MySQL Query Function?
I have a query, as shown below. Its a grouped query and I have a column called quantity in a products table. If the value in this table drops below zero I want the query to take zero as the quantity. Is this possible?.....

Mysql 4.x Week Function Fails
I think there is a bug in mysql 4:

select week("2003-08-15") from po.orders limit 1;

produces: 32

after:

set session default_week_format=3;

it produces: 33 (which is correct in the Netherlands)

The documentation states:

set global default_week_format=3; (As root!)

This command should set the default_week_format. This command fails:

mysql> set global default_week_format=3;
Query OK, 0 rows affected (0.00 sec)

mysql> select week('2003-08-14');
+--------------------+
| week('2003-08-14') |
+--------------------+
| 32 |
+--------------------+
1 row in set (0.00 sec)

This result is incorrect. It should be 33.

If I use:

mysql> set session default_week_format=3;
Query OK, 0 rows affected (0.00 sec)

mysql> select week('2003-08-14');
+--------------------+
| week('2003-08-14') |
+--------------------+
| 33 |
+--------------------+
1 row in set (0.00 sec)

This is result is correct...

I use mysql 4.0.14. I also did the same test on mysql 4.1 alpha, which has
the same results.

Harm de Laat
Informatiefabriek
The Netherlands

Is There A Addslashes()-type Function In Mysql Or Sql
I was wondering if there was a way to automatically add escapes to a string in either SQL standard or MySQL, such as addslashes() in PHP. I'm looking for something like the quote() function but without the need for quoted strings?

PHP/MySQL, No Longer Connecting To Db When In Function
I'm trying to clean up the code so that design changes will be easier. So, I've put the

$connection = mysql_connect($hostName,$username,$password) or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db($databaseName, $connection);

etcetera... with output commands in global functions().

But for some reason (why?), it no longer "reads" the original include with all the database variables. Is there a way to help these new functions "read" the previously set variables?

Is There A Addslashes()-type Function In Mysql Or Sql
I was wondering if there was a way to automatically add escapes to a
string in either SQL standard or MySQL, such as addslashes() in PHP. I'm
looking for something like the quote() function but without the need for
quoted strings?

Escaping Charater Function In Mysql
Is there any escaping character function available in mysql. I am creating report using stored procedure by concat various data's. Within the data's some special character found like (" ' ) i need to escape those character from mysql function.

UserDefined Function :MySQL Restarts
I am attempting to create a Function by means of using the following query create function xxxx returns integer so name yyyyy.so . The Function gets created Properly at the first time. But when i attempt to Create the same function again after dropping it the MySQL Server gets restarted and the function is not getting created. I don't know what will be problem.....Could any one give me a solution or  hint where will be the problem.

Problem Logging In Using Mysql Password Function
I have a test server on a windows box with php 4.3.10 and mysql 4.1.10-nt. I built a login app and It works well using the mysql password('') function. Unfortunately I ported the app to a freebsd box running php 4.3.10 and mysql 4.1.12. The passwords come out differently and I don't understand why.

For instance, the password test looks like "378b243e220ca493" on the windows box and the freebsd database entry look like "*94BDCEBE19083CE". As you can see, very different. And this causes a lockout from logging in.

Instead of being routed to a "safe" login page, the error for a wrong username/password combo shows up.

Why Does GROUP_CONCAT() Function Fail In MySQL 4.1.12 In This Query?
Here are my results using MySQL 4.1.12 and I honestly don't think this is right, but can't figure out what to do:

Stored Function Stops MySQL Service
I'm using MySQL 5, Windows XP Home SP2 (ack, but only for the near future)... I have what appears to be a simple and straightforward need- execute a function for a column in each row of a result set: Code:

SQLColumns Function And MySQL ODBC Driver
The MySQL ODBC driver returns an error when calling SQLColumns function with an empty Table parameter:

[MySQL][ODBC 3.51 Driver][mysqld-4.0.18-nt]Can't use wildcards in table name

Is there a newer version which supports wildcards in table name? Actually I don't really need wildcards, but I need to get the list of all columns in all tables.

How Can I Execute A PreparedStatement Inside Mysql Function
How can i execute a preparedStatement inside mysql function?

Wot Is The Function To Count The Records In Selelct Statmtn In MySQL
wot is the function to count the records in Selelct statement in MySQL?

Just like
PHP

mysql_num_rows($result);

in php.

Mysql Appears To Have Changed The 'password' Function Hashing
I've been using Mysql for about 6 months but in fairly basic fashion. For a cms I have built, I have a users table, with userName and password fields. An admin can create new users, and the password is hashed using the PASSWORD() function.
SQL: "INSERT INTO users VALUES ('', '$userName', PASSWORD('$userPwd'))

Straight out of the book basically. Now the problem is that all this has been functioning fine on a couple of sites on external servers, plus a couple of local machines.

Until today, on my main dev machine - yesterday a user could log in, today they couldn't. As far as I can tell, nothing has changed. But when I look at the hashes in the database table, they are 41 chrs, and when I add a new user, the hash is 16 characters.

I know that at some stage the hash length was increased between mysql versions, but I have not updated the install (I run XAMPP for Windows 1.4.14, which appears to install php 5.0.4 and mysql 4.1.12)

Is there any other reason that the hash length could change to 16? I'd like to know why this happened so that I'm prepared if it happens on the server (where it is not so easy to hack in and add new users that can log in again)

Linux Mysql Nfs : Bind On Unix Socket: Function Not Implemented
I have installed Mysql on red hat ES release 3 and i was working great.

For my applications, I decided to to put the data directory on another machine. The other machine is a big disk of storage (Adaptec snap server 1 terabyte)
It working great for all applications except Mysql

In fact, i put /var/lib/mysql on another machine and I made a nfs mount

When i try to start mysql i have this :

/etc/rc.d/init.d/mysqld start
Timeout error occurred trying to start MySQL Daemon.
Starting MySQL: [FAILED]

in the error message i have this

051028 11:12:33 mysqld started
051028 11:12:33 Can't start server : Bind on unix socket: Function not implemented
051028 11:12:33 Do you already have another mysqld server running on socket: /var/lib/mysql/mysql.sock ?
051028 11:12:33 Aborting

051028 11:12:33 /usr/libexec/mysqld: Shutdown Complete

051028 11:12:33 mysqld ended

I have verified the permission and everything seems to be ok....

User-defined Function: ERROR 2013 (HY000): Lost Connection To MySQL Server During Query
With mysql-4.1.1-alpha, using any User Defined Function ( UDF) at the
query execution stage, on Linux 2.6, gave me the following error:

"ERROR 2013 (HY000): Lost connection to MySQL server during query"

However, upgrading to mysql-4.1.2-alpha seemed to solve the problem.

Both versions were configured exactly as follows

../configure --with-openssl --enable-thread-safe-client --with-mysqld-ldflags
=-rdynamic

The only way I could solve this was by upgrading to 4.1.2-alpha-log. Then,
recompiling the functions, drop the old UDF functions, then, recreate.
So far so good.

Anyway, if you run into this problem, or just want more detail on the sample
User Defined Functions that come with MySQL ( /sql/udf_example.cc), I've put
my notes in the following link ( TIP 27 )

Warning: Mysql_connect() [function.mysql-connect]: Access Denied For User 'debscrof'@'localhost' (using Password: NO)
Have MySQL on a VPS running CPanel
MySQL v4.1.22-standard

Can access MySql fine through CPanel, phpMyAdmin etc all work fine, creating databases, deleting databases, adding users etc

However, when I try to use MySql from a website, it fails

I created a user "test1" (which then got the username "debscrof_test1" from CPanel), a password for the user "test2", and then added the user to a new database "testdb" with all priviliges

Then a simple script to connect to the database (as I am trying to locate the source of the errors), as per below:

<?php
$dbhost = "localhost";
$dbuser = "debscrof_test1";
$dbpass = "test2";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'debscrof_testdb';
mysql_select_db($dbname);
?>

Have tried with " and ' around the values, with 127.0.0.1 as the host... still with the same error message:

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'debscrof'@'localhost' (using password: NO) in /home/debscrof/public_html/testdb.php on line 6

Error connecting to mysql

...any suggestions why I cannot connect? (and why it says password: NO)!

Now() Function
I am using now function to get current date when info is added to my table. I am using a hosting provider that is 6 hrs ahead in time zone so i always have to subtract 6hrs to get the correct time. Is there anyway I can format the time to be inserted to my time zone?

Self Run Function/..
I need to delete some records from my table every 5 minutes. I thought that would be better if done via a trigger, function, etc. But I don't know how to fire a trigger every 5minutes or is there any other way to do that?

Using The AVG Function
I am trying to use this query:

SELECT average(price) FROM `data` WHERE id IN ( '3', '3', '6' )

to average the price of items users select. The problem is that when a user selects a value more than once it only includes it in the average once. How can I make it average all the values?


Copyright © 2005-08 www.BigResource.com, All rights reserved