MySQL,使用字段值作为别名

时间:2018-06-07 16:16:06

标签: mysql stored-procedures

我正在尝试设计一个存储过程,它将credentials加入两个表contactuser_id。在预期结果集中,contact提供来自两个字段(contact_typeaddress)的值,其中contact.contact_type值用作字段名称,并使用contact.address值作为价值观。这是代码:

CREATE PROCEDURE myProcedure()
BEGIN
start transaction;
set @v = null;
select
    credentials.*,
    concat('case when credentials.user_id = contact.user_id then contact.address end as ',contact.contact_type)
from credentials left join contact on credentials.user_id = contact.user_id
where credentials.user_id not in ('4510180001', '3870180002') into @v;

prepare stmt from @v;
execute stmt;
deallocate prepare stmt;
commit;
END

当我执行此代码时,出现错误:Error Code: 1222. The used SELECT statements have a different number of columns

当我按如下方式更改方案时:

CREATE DEFINER=`root`@`localhost` PROCEDURE `allUser`()
BEGIN
start transaction;
set @v = null;
select concat('select
    credentials.*,
    case when credentials.user_id = contact.user_id then contact.address end as ',contact.contact_type)
from credentials left join contact on credentials.user_id = contact.user_id
where credentials.user_id not in ('4510180001', '3870180002') into @v;

prepare stmt from @v;
execute stmt;
deallocate prepare stmt;
commit;
END

我收到错误:Error Code: 1172. Result consisted of more than one row

我正在寻找解决方案。感谢。

1 个答案:

答案 0 :(得分:0)

对于第一部分,您收到错误,因为您需要select...into与COLUMNS相同数量的变量。所以:

select
credentials.*,
concat('case when credentials.user_id = contact.user_id then contact.address end as ',contact.contact_type)

from credentials left join contact on credentials.user_id = contact.user_id
where credentials.user_id not in ('4510180001', '3870180002') into @v,@w,@x,@y;

..等等。对于查询返回的每一列,您都需要一个变量。

第二部分是类似的,除了你试图将多个ROWS放入变量。变量一次只能保存一个值/行。您需要在查询末尾添加LIMIT 1子句。

我猜这些答案都没有用,因为你试图准备一份陈述。在这种情况下,ENTIRE查询需要用concat包装,然后放入变量中。像这样:

select concat('select credentials.*,
case when credentials.user_id = contact.user_id then contact.address end as contact.contact_type
from credentials left join contact on credentials.user_id = contact.user_id
where credentials.user_id not in ('4510180001', '3870180002')) into @v;