簡體   English   中英

SQL查詢以檢索大於1的行值和相應的列名

[英]SQL Query to retrieve Row Values greater than 1 and Corresponding Column Names

我有一個看起來像這樣的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中。

可以使用交叉連接來完成此操作,但這並不是特別有效。 如果您沒有大量數據,這可能不是問題,但是如果您有大量數據,則可能需要考慮ETL數據或更改存儲設計。

Bluefeet對於如何實現此目標有一個很好的答案 針對您的解決方案的適應應如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM