douhongxie5436 2014-05-07 02:42 采纳率: 100%
浏览 17
已采纳

如何使用PHP中的PDO使用PDO从子表中获取信息?

How do I get information (via a parent table), from a child table that's using a foreign key that references the parent.

For example:

Table: user_list (parent)

-----------------------------
first_name | Last Name | ID |
-----------------------------
   john    | Appleseed |  4 |
           |           |    |

Table: user_info: (child)

----------------------------------------------
     email         |  password | userlist_ID |
----------------------------------------------
jappleseed@me.com  |   ******* |       4     |

Let's say I have John Appleseed's info stored in an array:

$johnsInfo;

How can I then retrieve John's email from the user_info table?

I'm trying this atm:

db->query("SELECT * FROM user_info WHERE userlist_ID = :ID", $johnsInfo);

Not sure if that's the right way of doing things though.

  • 写回答

2条回答 默认 最新

  • duanqianpu6499 2014-05-07 02:52
    关注

    If this is a real example, you should just make the two tables into one table. Generally if tables have 1:1 correspondence, you should put them together (though, there are special cases when you shouldn't).

    Anyway, you'd want to do something like:

    SELECT ul.*, ui.* FROM user_list ul
    LEFT JOIN user_info ui
      ON ui.userlist_ID=ul.ID
    WHERE ul.ID = :ID
    

    There are different kinds of joins. Check out the MySQL documents (http://dev.mysql.com/doc/refman/5.0/en/join.html) or search for something like "database joins" to find out which one will end up working for you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。