4

I was wondering if i can clean this up a bit, i wanted to make a nested sql statement but am unsure how.

$serverfile = mysqli_fetch_array(mysqli_query($link,"SELECT `Server_ID` 
    FROM `FileServerFiles` 
    WHERE `File_ID` ='$fileid' 
    limit 1"));
$server = mysqli_fetch_array(mysqli_query($link,"SELECT `ExternalDomain`,`AccessFile` 
    FROM `FileServers` 
    WHERE `ID` ='".$serverfile['Server_ID']."'"));

i wanted something like this?

    $server = mysqli_fetch_array(mysqli_query($link,"SELECT `ExternalDomain`,`AccessFile` 
        FROM `FileServers` 
        WHERE `ID` ='(SELECT `Server_ID` 
            FROM `FileServerFiles` 
            WHERE `File_ID` ='$fileid' 
            limit 1)'"
    ));
4

4 回答 4

2

这个查询应该这样做;由于您只查询一项,因此您实际上并不需要加入:

SELECT `ExternalDomain`,`AccessFile` 
FROM `FileServers` 
WHERE `ID` IN (SELECT `Server_ID` 
    FROM `FileServerFiles` 
    WHERE `File_ID` ='$fileid' 
    limit 1
);

顺便说一句,我假设它$fileid已经过适当的消毒;您还可以考虑准备好的陈述(和/或)。

于 2013-04-23T11:26:45.593 回答
1

你可以试试IN,

 $server = mysqli_fetch_array(mysqli_query($link,"SELECT `ExternalDomain`,`AccessFile` FROM `FileServers` WHERE `ID` IN (SELECT `Server_ID` AS ID FROM `FileServerFiles` WHERE `File_ID` ='$fileid' limit 1)"));
于 2013-04-23T11:16:53.983 回答
0

这不是嵌套的,而是使用join语法的等价物,有时被认为更简洁(而且现代,值得一提)。可能不是您想要的,但在这里供您参考(因为如果您使用数据库,您可能会遇到这种语法)。

INNER JOIN意味着如果联接右侧没有匹配的行,则从结果中丢弃联接左侧的行。

我已经添加了大量的空白空间,所以很清楚,请随意删除它。但没必要。

$server = mysqli_fetch_array(mysqli_query($link,
   "SELECT 
       fs.ExternalDomain,
       fs.AccessFile

    FROM 
       FileServers fs

       INNER JOIN FileServerFiles fsf
       ON fs.fileid = fsf.server_id

     WHERE 
       fsf.File_ID ='$fileid' 

     LIMIT 1
   "));

正如@Jack 在我之前提到的,您应该确保$fileid已消毒。参考http://en.wikipedia.org/wiki/SQL_injection

于 2013-04-23T11:22:03.303 回答
-2

语法可能有点不对劲,但左连接应该可以解决问题。旁观者认为较短,但一个查询优于 2 个。

$serverfile = mysqli_fetch_array(mysqli_query($link,"
    SELECT f.`Server_ID`, s.`ExternalDomain`, s.`AccessFile`
    FROM `FileServerFiles` f 
    LEFT JOIN `FileServers` AS s ON s.`ID` = f.`Server_ID` 
    WHERE f.`File_ID` ='$fileid'
    LIMIT 1
  "));
于 2013-04-23T11:18:53.637 回答