开发者

MySQL: LEFT JOIN or UNION table and set column value as column name?

开发者 https://www.devze.com 2023-04-13 06:30 出处:网络
Okay, so I know I might get reamed for even suggesting such a thing, but it has me curious... Let\'s suppose I have a table like:

Okay, so I know I might get reamed for even suggesting such a thing, but it has me curious...

Let's suppose I have a table like:

content
---------------
| id | status |

and a table like this:

attributes
---------------------------
| id | pid | name | value |

where some attributes might be

| 1 | 1 | status | published |
| 2 | 1 | v开发者_运维百科iable | yes       |

Is is possible to do query so that the value in the NAME column of attributes would be represented as a column name?

Example:

SELECT a.name AS {a.name value} FROM content c LEFT JOIN attributes a ON a.pid = c.id

So when I run through the results I could do something like

foreach($result as $r){
    echo $r->viable;  //yes
    echo $r->status;  //published
}

I know this doesn't follow relational databasing, but it would be useful to me for some superfluous attributes. The other option I thought of was storing the data as a serialized string, but that makes me cringe.


MySQL does not have native support for pivot queries, and it cannot pivot an arbitrary number of rows into columns because the columns have to be known ahead of time. In other words, you have to do this with PHP.

I'm not sure whether multiple objects can be returned from your query or not (each object would hopefully be only one row, but you've already admitted to a lack of normalization). If only one is going to be returned each time, it's even simpler. However, I'm going to assume more than one can be returned and they are keyed on pid:

$content = array();
while ($row = $result->fetch()) {
   //Prevent a PHP warning; this step can be skipped
   if (!isset($content[$row->pid])) {
      $content[$row->pid] = array();
   }

   $content[$row->pid][$row->name] = $row->value;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消