从另一个表中选择服务器名称

时间:2012-06-03 22:25:59

标签: php mysql sql codeigniter join

我有两个表,filesservers。这是架构:

f_id, s_id, u_id, name, size, downloads, uploaded

s_id, name, description, disk_space, used_space, enabled

现在,我正在尝试获取有关特定文件以及托管服务器的信息。在files表中,这由s_id列确定,该列是servers表的外键。我想检索文件名称,大小,上传时间以及它所在的服务器。我试过这个:

public function get_file_details()
{
    $sql= 'SELECT name, size, uploaded, server
           FROM `files` f
           JOIN `servers` s
           ON f.s_id = s.u_id
           WHERE f_id = ?
           LIMIT 1';
}

但它不起作用。我做错了什么?

2 个答案:

答案 0 :(得分:1)

public function get_file_details()
{
    $sql= 'SELECT f.name, size, uploaded, s.name
           FROM `files` f
           JOIN `servers` s
           ON f.s_id = s.s_id
           WHERE f_id = ?
           LIMIT 1';
}

3个更改:name => f.name,server => s.name,ON f.s_id = s.u_id => ON f.s_id = s.s_id

答案 1 :(得分:1)

它显示此错误,因为名称字段存在于两个表中,因此它变得不明确。要避免此错误,请始终添加表名别名 试试这个

SELECT f.name, f.size, f.uploaded, s.name
           FROM `files` f
           JOIN `servers` s ON f.s_id = s.s_id
           WHERE f_id = ?
           LIMIT 1'