douyaosi3164 2011-04-28 11:07
浏览 39
已采纳

mysql新手:sql选择问题

Guys, good day. im starting to learn mysql and still fiddling around. I just saw a table structures just like the example. How can i achieve an array querying in sql when i use var_dump in php? more power!

Table: categories
id |  name  |
1  |  Cat A |
2  |  Cat B |

Table: sub_categories
id | category_id |   name      |
1  |     1       |  Sub Cat A  |
2  |     2       |  Sub Cat B  |

array
  'Cat A' => 
      array
        1 => string 'Sub Cat A' (length=9)
  'Cat B' => 
      array
        2 => string 'Sub Cat B' (length=9)
  • 写回答

1条回答 默认 最新

  • doujiurong7210 2011-04-28 11:20
    关注

    You have to loop over your category table and then select all rows from this category and fill up your array.

    You could also use JOIN like in the example below (leave out the where part if you want all categories):

    $result = mysql_query("SELECT categories.name as catname
        , categories.id as catid
        , sub_categories.id as subcatid
        , sub_categories.name as subcatname 
      FROM categories 
      LEFT JOIN sub_categories ON sub_categories.category_id = categories.id 
      WHERE categories.id = 1");
    
    $rows = mysql_fetch_object($result);
    $result = array();
    foreach($rows as $row) {
      $result[$row->catname][] = array(
         'id' => $row->subcatid,
         'category_id' => $row->catid,
         'name' => $row->subcatname
      );
    }
    
    var_dump($result);
    

    UNTESTED but should work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一道python难题2
  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备