doudi5291 2013-09-30 11:56
浏览 14
已采纳

PHP PDO正确使用JOINS进行mySQL查询

How would one correctly use a JOIN to add each row that matches the ID from a second table in as a column header of the first table.

Example.

THEME TABLE

ID     TITLE    DATE    TEXT
1     logo     23101    some sample text
2     back     23101    some sample text

THEME_META Table

refID     field     value
1         width     300
1         height    190
1         alt       some alternate text
2         bgcolor   #222

MySQL query would then be SELECT * FROM theme WHERE date = ?

I would then have foreached my results and have my theme item in a variable which I can use to echo the value for any column in the row.

eg. echo $theme['title'];

How would I also be able via a JOIN to be able to echo

$theme['width'] . $theme['height'] . $theme['alt']
  • 写回答

1条回答 默认 最新

  • dongxuan1314 2013-09-30 12:00
    关注

    What you are looking for is pivot the column field in the theme_meta table for each refID, unfortunatly, MySQL doesn't have the pivot table operator, but you can use the CASE expression to do so:

    SELECT
      t.id,
      t.date,
      t.text,
      MAX(CASE WHEN m.field = 'width' THEN m.value ELSE NULL END) AS Width,
      MAX(CASE WHEN m.field = 'height' THEN m.value ELSE NULL END) AS height,
      MAX(CASE WHEN m.field = 'alt' THEN m.value ELSE NULL END) AS alt, 
      MAX(CASE WHEN m.field = 'bgcolor' THEN m.value ELSE NULL END) AS bgcolor,
    FROM theme AS t
    INNER JOIN theme_meta AS m ON t.id = m.refID
    GROUP BY t.id,
      t.date,
      t.text;
    

    Update: To do this dynamically instead of listing the values manually, you have to use dynamic sql, like this:

    SET @sql = NULL;
    SELECT
      GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(m.field  = ''',
          m.field, ''', m.value, NULL)) AS ', '''', m.field  , '''')
      ) INTO @sql
    FROM theme_meta AS m;
    
    SET @sql = CONCAT('SELECT t.id,t.date,t.text, ', 
                      @sql , '
        FROM theme AS t
    INNER JOIN theme_meta AS m ON t.id = m.refID
    GROUP BY t.id,
      t.date,
      t.text;');
    
    prepare stmt 
    FROM @sql;
    
    execute stmt;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错