4

I would like to write a mysql function that takes an integer as input and that function execute a select statements "select id from table_name" then i want that function return the result of select statements.

then

in query i want to do smthing like:

select id,name from table_name where id in (call function here that returns a list of ids).

Is that valid in mysql ??

Thanks in Advance

5 Answers 5

1

No, you cannot do this in MySQL.

A MySQL procedure that returns a resultset cannot be used in a subquery.

If your function is just a number of SELECT statements, you can do something like this instead:

SELECT  id, name
FROM    mytable1
WHERE   id IN
        (
        SELECT  id
        FROM    mytable2
        WHERE   value = @myinteger
        UNION ALL
        SELECT  id
        FROM    mytable2
        WHERE   value = @myinteger
        UNION ALL
        …
        )

or, which is more efficient,

SELECT  id, name
FROM    mytable1 t1
WHERE   EXISTS
        (
        SELECT  NULL
        FROM    mytable2 t2
        WHERE   t2.id = t1.id
                AND t2.value = @myinteger
        UNION ALL
        SELECT  NULL
        FROM    mytable3 t2
        WHERE   t3.id = t1.id
                AND t3.value = @myinteger
        UNION ALL
        …
        )
Sign up to request clarification or add additional context in comments.

Comments

1

Yes you can use subqueries in MySql

something like following

select id,name from table_name1 
               where id in (select DISTINCT(table_name1_id) from table_name2)

1 Comment

in my case i cant use subquires because the subquery contains union so it work with "in" clause.
0

You dont need a function, you can use a subquery.

E.g.

select id,name from table_name where id in (select someIds from othertable)

Comments

0

Sure. You can use a Stored Procedure, a UDF or even a subquery.

Have a look:

  1. MySQL 5.5 Reference Manual - Stored Procedures
  2. MySQL 5.5 Reference Manual - Subqueries
  3. MySQL Stored Procedures: Part 1

Comments

0

If you really need to use a function, you can:

CREATE FUNCTION my_func (in_id INT(11), value INT(11)) RETURNS INT(11) DETERMINISTIC 
RETURN in_id IN (SELECT id FROM table_name WHERE id = value);

and you would call it with this:

SELECT id,name from table_name where myfunc(id, 1);

It is generally slow because MySQL can't optimize its use, but does the job.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.