【问题标题】:Something analogous to a symlink in MySQL?类似于 MySQL 中的符号链接的东西?
【发布时间】:2011-12-23 22:46:17
【问题描述】:

是否可以在记录中存储指向另一条记录的“链接”?例如:

table USERS
id    name    link
-------------------------------------------------------
1     user1   [link to record with id=4 in table info]

所以,在 PHP 中,我可以这样做:

// connect to the database etc....
$query          = "select * from users where id=1";
$result         = mysql_query($query);
$another_result = mysql_result($result, 0, 'link');

这样$another_result 会以与使用mysql_query() 调用相同的原始格式存储另一个查询的结果。

这可能吗?

【问题讨论】:

  • 也可以称之为 SQL:$another_result = mysql_result(mysql_query($result[0]['link']));

标签: php mysql sql record


【解决方案1】:
$query          = "select info.* from info 
                   inner join users on users.link = info.id 
                   where users.id=1";
$result         = mysql_query($query);

使用JOIN 是SQL 的基本组成部分,就像在PHP 中使用for 循环一样。

阅读无畏领袖的A Visual Explanation of SQL Joins

【讨论】:

    【解决方案2】:

    也许你的意思是一个指向另一个表中另一个键的键,所以例如你可以有这样的东西:

    table USERS
    id    name    info_id
    -------------------------------------------------------
    1     user1   4
    
    table INFO
    id    info    
    --------------
    4     someinfo
    

    通过 JOIN,您可以获得例如带有“链接”字段的结果集:

    SELECT u.name AS name, i.info AS info
    FROM USERS u
    JOIN INFO i ON u.info_id = i.id  
    

    【讨论】:

      【解决方案3】:

      MySql 是所谓的关系数据库,表之间的关系(链接)是关键概念之一。在您的特定情况下,您想要的“链接”称为外键。您可能想要a read here(如果您在 google 上查看,还有更多文章)。

      您可以通过JOIN operation 检索链接的记录,正如其他回答者已经告诉您的那样。

      【讨论】:

        猜你喜欢
        • 2011-08-14
        • 1970-01-01
        • 2020-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多