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

报告相同问题?

悬赏问题

  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题
  • ¥15 Selenium+docker Chrome不能运行
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到