繁体   English   中英

mysql获取列名并与另一个表进行比较

[英]mysql getting column name and compare with another table

我有两张桌子

表A

Date | A001 | B001
-------------------
2020 |  2   |  3

表b

ItemCode | ItemName
---------------------
   A001  |   candy
   B001  |   Apple

是否可以从表 A 中选择数字以及从表 B 中选择实际的 itemName? 英语中的语句类似于

select * from table A and itemName from table B where TableA's columnName = TableB's ItemName;

如果我正确地跟随您,您可以执行以下操作:

select a.*, ba.item_name item_name_a, bb.item_name item_name_b
from a
left join b ba on ba.item_code = 'A001'
left join b bb on bb.item_code = 'B001'

或者您可以使用子查询:

select
    a.*,
    (select item_name from b where item_code = 'A001') item_name_a,
    (select item_name from b where item_code = 'B001') item_name_b
from a

我猜你只想替换标题,所以使用 information_schema.columns 和动态 sql

set @sql = (select concat('select date,',
        aa.gc1,
        ' from (',
        replace(substring(bb.gc2,1,length(bb.gc2) - length('union all')),'union all,','union all '),
        ') s group by date'
        )
from
(
select 
        group_concat(
         'max(case when itemname = ',char(39),itemname,char(39),' then value  end) as ',itemname
         ) gc1
from
(
select itemname , column_name from information_schema.columns 
join   t1 on t1.itemcode = column_name
where table_name = 't'
and column_name in (select distinct itemcode from t1)
) a
) aa
cross join
(
select 
        group_concat(
         'select date,',char(39),itemname,char(39),' as itemname,', column_name,' as value from t  union all'
         ) gc2
from
(
select itemname , column_name from information_schema.columns 
join   t1 on t1.itemcode = column_name
where table_name = 't'
and column_name in (select distinct itemcode from t1)
) b
) bb
) ;

prepare sqlstmt from @sql;
execute sqlstmt;
deallocate prepare sqlstmt;

+------+-------+-------+
| date | candy | Apple |
+------+-------+-------+
| 2020 |     2 |     3 |
+------+-------+-------+
1 row in set (0.001 sec)

暂无
暂无

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

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