:::

9-2 同時讀取兩個資料表

一、用join一次讀兩個以上的資料表

  1. 關聯資料表方便的地方就是:一次可以讀取兩個以上的資料表,簡易語法如下:
    SELECT a.* , b.* , c.*
    FROM `資料表1` as a
    JOIN `資料表2` as b ON a.`索引欄位`= b.`索引欄位`
    JOIN `資料表3` as c ON b.`索引欄位`= c.`索引欄位`
    WHERE a.欄位='值' AND ….
    
  2. 「left join」代表以左邊為主,順便到右邊撈撈看有無指定的資料。
  3. 「right join」代表以右邊為主,順便到左邊撈撈看有無指定的資料。
  4. 「join」代表兩邊都要同時有資料,否則該筆資料不會出現。
  5. 以本例而言,讀出報名者編號,順便讀出報名者資料的寫法:
    //區塊主函數:列出所報者
    function list_signup($options)
    {
        global $xoopsDB;
        if ($_GET['action_id']) {
            $signups_tbl = $xoopsDB->prefix('signups');
            $users_tbl   = $xoopsDB->prefix('users');
            $action_id   = intval($_GET['action_id']);
            $sql         = "SELECT a.*, b.* FROM `{$signups_tbl}` AS a
            JOIN `{$users_tbl}` as b ON a.`uid` = b.`uid`
            WHERE a.`action_id` = '{$action_id}'";
            $result  = $xoopsDB->query($sql) or web_error($sql);
            $signups = [];
            while ($val = $xoopsDB->fetchArray($result)) {
                $signups[] = $val;
            }
            return $signups;
        }
    }
  6. 此處用 join,表示一定要有會員資料,否則就不秀出來。

二、修改樣板

  1. 修改 \templates\side_signups.tpl 把 uid 改成 name就可以了,這裡順便加上 Email
    <table class="table table-hover table-striped">
      <thead>
        <tr class="info">
          <th>姓名</th>
          <th>Email</th>
        </tr>
      </thead>
      <tbody>
      <{foreach from=$block item=signup}>
          <tr>
            <td><{$signup.name}></td>
            <td><{$signup.email}></td>
          </tr>
      <{foreachelse}>
        <tr>
          <td colspan=2>暫無人報名</td>
        </tr>
      <{/foreach}>
      </tbody>
    </table>

     


:::

書籍目錄

展開 | 闔起

http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D29%26tbdsn%3D907

計數器

今天: 2102210221022102
昨天: 1988198819881988
總計: 7388993738899373889937388993738899373889937388993