mysql 用于检索大于1的行值和相应列名的SQL查询

uelo1irk  于 2023-03-28  发布在  Mysql
关注(0)|答案(1)|浏览(131)

我有一个MYSQL(phpmydamin)数据库表,它看起来像这样,我试图检索关于特定行的大于1的值以及与这些设置值对应的列名的信息。我基本上是试图找出学生持有的物品以及数量。

username      item1 item2 item3 item4 item5 item6 item7

n000111         1      0     1     1    1     1     1

n010554         0      0     3     2    0     0     0

n010555         1      0     4     0    0     1     1

n010556         0      0     0     0    0     0     0

n010557         0      8     0     2    0     1     0

例如,如果我发送用户名“n010555”到我的phpscript来从这个表中获取数据,我期待这样的反馈:

n010555
item1 - 1
item3 - 4
item6 - 1
item7 - 1
total - 7

类似的事,我会很感激你的帮助。先谢谢你了。

8yparm6h

8yparm6h1#

您需要做的是取消透视数据,不幸的是,您的数据存储在MySQL中,它没有这样的功能。
这可以使用交叉连接来完成,但效率不是特别高。如果你没有大量的数据,这可能不是一个问题,但如果你有一个不平凡的数据量,你可能需要考虑ETling数据或改变你的存储设计。
Bluefeet有一个很好的answer,它可以帮助你实现这个目标。你的解决方案的适应性如下所示:

select t.id,
  c.col,
  case c.col
    when 'item1' then item1
    when 'item2' then item2
    when 'item3' then item3
    when 'item4' then item4
    when 'item5' then item5
    when 'item6' then item6
    when 'item7' then item7
  end as data
from yourtable t
cross join
(
  select 'item1' as col
  union all select 'item2'
  union all select 'item3'
  union all select 'item4'
  union all select 'item5'
  union all select 'item6'
  union all select 'item7'
) c
where
  username = :username

相关问题