【问题标题】:SQL Query to retrieve Row Values greater than 1 and Corresponding Column NamesSQL 查询以检索大于 1 的行值和对应的列名
【发布时间】:2017-10-27 17:53:18
【问题描述】:

我有一个看起来像这样的 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

类似的东西,我将非常感谢您的帮助。提前致谢。

【问题讨论】:

  • 您在数据库的其他地方是否有此数据的非扁平化存储?如果没有,考虑到数据库的选择,这将不是一个简单的查询。 MySQL 不适合这样的事情。

标签: mysql database rows columnname


【解决方案1】:

您需要做的是反透视您的数据。不幸的是,您的数据存储在 MySQL 中,它没有这样的功能。

这可以使用交叉连接来完成,但效率不是特别高。如果您没有大量数据,这可能不是问题,但如果您有大量数据,则可能需要考虑对数据进行 ETL 处理或更改存储设计。

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

【讨论】:

  • 嗨雅各布,谢谢。您认为手动将我的列转换为行并将行转换为表中的列会使这更容易完成吗?
  • @David 一般来说,是的。扁平化的数据适合用于报告,但它不是存储您想要像这样查询的数据的好方法。
  • 好的,非常感谢。我会这样做的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-28
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多