如何在查询表中使用行作为MySQL查询中的列?

时间:2010-05-12 13:47:08

标签: mysql

我正在尝试构建一个MySQL查询,该查询使用查找表中的行作为结果集中的列。

LookupTable中

id  |  AnalysisString
1   |  color
2   |  size
3   |  weight
4   |  speed

ScoreTable

id  |  lookupID | score | customerID
  1 |      1    |   A   |     1
  2 |      2    |   C   |     1 
  3 |      4    |   B   |     1 
  4 |      2    |   A   |     2
  5 |      3    |   A   |     2
  6 |      1    |   A   |     3 
  7 |      2    |   F   |     3

我想要一个查询,它会将相关的lookupTable行用作查询中的列,以便我可以得到如下结果:

customerID |  color  | size  | weight  | speed
     1          A        C                 D
     2                   A        A    
     3          A        F

问题的关键是可能会在LookupTable中添加其他行,并且查询应该是动态的,并且不会对查找ID进行硬编码。也就是说,这将有效:

SELECT st.customerID, 
(SELECT st1.score FROM ScoreTable st1 WHERE lookupID=1 AND st.customerID = st1.customerID) AS color,
(SELECT st1.score FROM ScoreTable st1 WHERE lookupID=2 AND st.customerID = st1.customerID) AS size,
(SELECT st1.score FROM ScoreTable st1 WHERE lookupID=3 AND st.customerID = st1.customerID) AS weight,
(SELECT st1.score FROM ScoreTable st1 WHERE lookupID=4 AND st.customerID = st1.customerID) AS speed
FROM ScoreTable st
GROUP BY st.customerID

直到LookupTable中添加了第五行。 。 。

也许我打破了整个关系模型,并且必须在后端PHP代码中解决这个问题?

感谢指导/指导。

汤姆

2 个答案:

答案 0 :(得分:1)

您已经构建了一个EAV数据库。在可维护性,效率和正确性方面做好很多准备。 “这是数据建模中的设计异常之一。” (http://decipherinfosys.wordpress.com/2007/01/29/name-value-pair-design/

最好的解决方案是将数据库重新设计为更正常的东西。

答案 1 :(得分:1)

您尝试执行的操作通常称为交叉制表符或交叉表查询。有些DBMS直接支持交叉表,但MySQL不是其中之一,AFAIK(有一篇博客文章here描述了模拟效果的艰难过程。)

有两种选择可以解决这个问题:

  1. 根本不要交叉。而是按行id,然后是AnalysisString对输出进行排序,并使用编程语言生成表格输出。
  2. 在编程语言中即时生成代码以发出适当的查询。
  3. 按照我上面提到的博客来实现服务器端解决方案。
  4. 还要考虑@ Marek的回答,这表明您可能最好重构模式。然而,建议不是给定的。有时,键值模型适合于手头的问题。