2

Is there any way to do that in a single query? Or do I have to manage it externally? It is not a JOIN of any kind.

SELECT
IF (
    (SELECT indicator FROM configuration_table) = 1,
    (SELECT series_id FROM series_table LIMIT 1),
    ''
) as if_exp
FROM
    series_table

This executes but returns the first ID over and over, and if I take out the LIMIT 1, it doesn't work as it expects only one result. But what I need is that, if this condition is met:

(SELECT indicator FROM configuration_table) = 1,

Then I need all this data returned:

SELECT series_id, series_code, series_name FROM series_table

Is it possible somehow? Should I be doing two queries and managing the data from php? Thank you very much.

Tyrannogina
  • 593
  • 1
  • 4
  • 21
  • Possible duplicate of [IF Condition Perform Query, Else Perform Other Query](http://stackoverflow.com/questions/17199604/if-condition-perform-query-else-perform-other-query) – Emdadul Sawon Jul 18 '16 at 07:46
  • I didn't see that question, sorry!! Still I don't manage to make it work with the answers in that question... – Tyrannogina Jul 18 '16 at 08:45

2 Answers2

3

The easiest way would be:

IF ((SELECT indicator FROM configuration_table) = 1) THEN
    SELECT series_id, series_code, series_name FROM series_table
END IF

You did not show us what to do, when the condition is false. We do not know the relationship between configuration_table and series_table, so we can't find a way to make it in a single query.

KaeL
  • 3,639
  • 2
  • 28
  • 56
  • It is not allowing me to start the query with an IF. Answering your question, if the condition is false I don't care much about what it does, whatever I can use to identify the condition wasn't met. – Tyrannogina Jul 18 '16 at 08:33
  • Because you can only execute `IF-ELSE` statements inside a `stored procedure`. You can create one, put inside the query I posted, and execute it. Just drop the stored procedure if you're done. – KaeL Jul 18 '16 at 08:39
1

I have copied this answer from IF Condition Perform Query, Else Perform Other Query this answer.

SELECT CASE WHEN ( (SELECT indicator FROM configuration_table) = 1 )
  THEN 
    SELECT series_id, series_code, series_name FROM series_table
  ELSE 
    <QUERY B>
END

Here Query B should replaced by your desired query.

Community
  • 1
  • 1
Emdadul Sawon
  • 5,730
  • 3
  • 45
  • 48
  • I don't know if I am doing something wrong, but it gives me an error at the SELECT right after THEN. I tried putting the SELECT statement inside parenthesis, but it keeps returning an error at that line (and I have checked the previous parenthesis too). – Tyrannogina Jul 18 '16 at 08:44
  • A comment I had was causing the error, but after I took it out, it happened as in my query: it only allows `SELECT series_id, series_code, series_name FROM series_table` to return one column and one row, otherwise it returns an error. – Tyrannogina Jul 18 '16 at 09:27