duanpin2034 2012-06-12 05:20
浏览 32
已采纳

mySQL - 在单个选择中使用xref表从相关表中获取数据

I have two tables, A and B which are xref'd together in AB_xref. At the moment to get data from table B I'm dumping all rows rows from A into an array and then looping over each index finding the multiple B rows that relate to that A row. I'm then stitching the rows from B into the array of rows from A - creating a nested array.

Is there any way to do this using a single select and conditions?

  • 写回答

1条回答 默认 最新

  • duanmao1919 2012-06-13 02:18
    关注

    See if this gets you somewhere close to where you want to be:

    Query:

    SELECT
       packages.name AS package_name,
       activities.name AS activity_name
    FROM
       package_activity_xref pax
    INNER JOIN packages ON packages.id = pax.package_id
    INNER JOIN activities ON activities.id = pax.activity_id
    

    PHP:

    $results = get_assoc_array_from_sql($your_query);
    $outputArray = array();
    
    foreach($results as $result) {
       if (array_key_exists($result['package_name'], $outputArray)) {
          // we already have an array at this package, push the new item
          array_push($outputArray[$result['package_name']], $result['activity_name']);
       } else {
          // the target array doesn't exist yet, make it
          $outputArray[$result['package_name']] = array($result['activity_name']);
       }
    }
    

    Basically, this code will loop through the entire xref table once (O(n) where n is the number of records in xref). For each record, it will look at the package name and see if the key exists in $outputArray yet. If it does not, make the value at that key an array with the current activity name. If it does exist, append the current activity to that array.

    If you do a print_r($outputArray) after execution, you should see an array with x items where x is the number of distinct packages. Each element in the array will be another array with y elements where y is the number of activities for the given package.

    Note: you will need to implement get_assoc_array_from_sql yourself but I assume you either have some implementation you are using already or you are using mysqli_fetch_assoc() or something similar.

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

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口