如何使用其中的一个公共字段从数据库连接三个表。(Mysql)

时间:2011-09-23 05:45:07

标签: php mysql sql

这是三个表

1. table `p_transactions` has following fields

(`txn_id`, `txn_uid`, `txn_bid_no`, `txn_date`, `txn_desc`, `txn_amt`, `txn_fee`, `txn_mode`, `txn_status`, `txn_mdate`)

2 . table `p_game_results` has following fields.

(`id`, `game_id`, `game_combo`, `game_combo_hr`, `cdate`, `mdate`)

3. Table `p_game_room_results` has following fields

 (`id`, `game_id`, `room_id`, `txn`, `round`, `result`, `score`, `cdate`, `mdate`)

我想使用他们的txn id作为公共字段加入他们。

这是我尝试过的东西。但不确定,我确定是错的。

$sql    = "SELECT * FROM " . $prefix . "_user_game_results".$prefix."_game_room_results".$prefix."_transactions WHERE". $prefix . "_user_game_result.uid"='$prefix."_game_room_results.id"'. and .$prefix."_transactions.txn_uid"='$prefix."_game_room_results.uid"'"";
        $result = $this->sql_fetchrowset($this->sql_query($sql));

感谢。

2 个答案:

答案 0 :(得分:1)

这应该这样做:

select * from p_transactions pt 
inner join p_game_room_results pgrr on pgrr.txn=pt.txn_id 
inner join p_game_results pgr on pgr.game_id=pgrr.game_id

通过公共字段加入所有表格。 p_game_room_resultsp_game_results加入游戏ID,因为这似乎是常见的字段。

答案 1 :(得分:0)

    select * 
    from p_transactions as p_t INNER JOIN p_game_results as p_g_r
    ON p_t.txn_id = p_g_r.id
    INNER JOIN
    p_game_room_results as p_g_r_r
    ON p_g_r_r.game_id = p_g_r.game_id;

以下别名用于INNER JOIN

   p_transactions as p_t
   p_game_results as p_g_r
   p_game_room_results as p_g_r_r

我建议你仔细阅读这些有用的SQL联接教程

http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

http://en.wikipedia.org/wiki/Join_%28SQL%29