简体   繁体   中英

Is there any way to execute a SELECT only if a condition in a different table is met?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM