【问题标题】:Hide columns from SELECT clause conditionally有条件地从 SELECT 子句中隐藏列
【发布时间】:2014-01-13 04:50:39
【问题描述】:

我想有条件地从 MySQL 存储过程中的 SELECT 子句中隐藏列。查询是

SELECT year,gwp_amount,claim_amount,cancellation_amount from tmptable;

我想有条件地显示gwp_amount,claim_amount,cancellation_amount 列,

有时我想显示gwp_amount and claim_amount 列,

有时gwp_amount and cancellation_amount 列,

有时one of the column

有时all three columns

我在存储过程中传递了三个指标,例如 gwp_ind、calim_ind、cancellation_ind。

我想根据这些参数显示这些列。

【问题讨论】:

  • 您希望输出是什么样的?根据定义,关系中的所有行都具有相同的列集。

标签: mysql


【解决方案1】:

我想你正在寻找Control Flow Functions

SELECT year, (IF gwp_amount < 2, NULL, gwp_amount) FROM tmptable;

如果要使投影有条件,则必须在应用程序中通过动态创建 SQL 查询来执行此操作。 IE。您必须为每种情况分别提出单独的查询。仅使用 SQL 是不可能的。您可以做的最接近的事情是在其列数中没有条件的查询。例如:

SELECT (IF gwp_amount < 2, gwp_amount, claim_amount) FROM tmptable;

这会在gwp_amountclaim_amount 上进行投影。但是不可能制作出gwp_amountgwp_amountclaim_amount 的东西。

【讨论】:

  • 感谢您的回复,如果我可以使用 IF,那么我只能显示一列,例如 if (gwp_ind, gwp_amount, claim_amount)。这不是我的问题,我有时想显示多个列。我可以在过程中使用 IF 语句来实现我的目标,但这不是好的编程习惯。比如如果 gwp_ind 然后 SELECT year,gwp_amount from tmptable else if gwp_ind and claim_ind then SELECT year,gwp_amount,claim_amount from tmptable end if;等等。但我认为这不是一个好习惯。
  • @KamranAslam,您想动态显示列吗?我认为这是不可能的。
【解决方案2】:

您可以使用 CASE 语句.... SELECT year, (CASE when gwp_ind = True THEN gwp_amount,当 calim_ind= True THEN claim_amount,当 cancel_ind = True THEN cancel_amount ELSE 0 END) as amount 来自 tmptable;

如果您有根据您的要求,您可以使用上述查询。 但是根据问题我们不能动态选择列 SELECT 子句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多