从条件相同的表中获取列名

时间:2019-04-04 09:18:02

标签: mysql sql

我需要表中满足条件的列名。 假设名为“ size”的列的值是“ 22”,而它应该在以“ sizecaption1,sizecaption24”开头的24列中检查相同的值,然后返回每一行的值都为“ 22”的列名。谢谢这是我尝试过的方法,但不适用于我:

create procedure dataaudit()
begin
declare countr  int;
declare headr  int;
set @countr = (select size from joinbom group by stylecode limit 0,1);
set @headr1=(select sizecaption1 from joinbom group by stylecode limit 0,1);
while @countr  = @headr1 do select column_name from 
information_schema.columns where table_name like'joinbom' and 
@countr=@headr;

1 个答案:

答案 0 :(得分:0)

根据您的稀疏规范,您可以尝试

SELECT
  id,
  TRIM(CONCAT(
    IF(sizecaption1 = size, 'sizecaption1 ', ''),
    IF(sizecaption2 = size, 'sizecaption2 ', ''),
    IF(sizecaption3 = size, 'sizecaption3 ', ''),
    IF(sizecaption4 = size, 'sizecaption4 ', ''),
    IF(sizecaption5 = size, 'sizecaption5 ', ''),
    IF(sizecaption6 = size, 'sizecaption6 ', '')
    )) AS result
FROM JoinBoom
ORDER BY id
;

查看实际情况:SQL Fiddle

如果且因为这需要调整/进一步的细节,请发表评论。