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条)

报告相同问题?

悬赏问题

  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃