简体   繁体   English

仅当满足不同表中的条件时,才有任何方法可以执行SELECT吗?

[英]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. 它不是任何一种JOIN。

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. 这将执行,但是一遍又一遍地返回第一个ID,如果我取出LIMIT 1,它将无法正常工作,因为它只期望一个结果。 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? 我应该做两个查询并管理来自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. 我们不知道configuration_tableseries_table之间的关系,因此我们找不到在单个查询中实现该关系的方法。

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. 在这里, Query B应该替换为您想要的查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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