如何使用查询结果选择到Sql Server中的另一个表

时间:2014-06-03 15:28:14

标签: sql sql-server

嗨,我是新来的。我在将查询结果选择到另一个数据库时遇到问题。

<?php
include_once("config.php");
$connectionInfo = array( "Database"=>"rohanstat", "UID"=>$UID, "PWD"=>$PASS);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$sql2 = "SET ROWCOUNT 15 SELECT   attacker, COUNT(attacker) AS dupe_cnt FROM [rohanstat].[dbo].[TPKill]
GROUP BY attacker
HAVING   COUNT(attacker) > 0
ORDER BY COUNT(attacker) DESC";
$stmt2 = sqlsrv_query( $conn, $sql2);
while($rows = sqlsrv_fetch_array($stmt2))
echo $rows ['attacker']."<br>";
?>

我只想使用$rows['attacker']来选择另一个数据库。这意味着我想像这样使用它。

sql = "select * from [RohanGame].[dbo].[TCharacter] where name = $rows ['attacker'];

提前致谢。

3 个答案:

答案 0 :(得分:0)

您只需使用IN

即可
SELECT  *
FROM    [RohanGame].[dbo].[TCharacter] 
WHERE   name IN 
        (   SELECT   TOP 15 attacker
            FROM [rohanstat].[dbo].[TPKill]
            GROUP BY attacker
            HAVING   COUNT(attacker) > 0
            ORDER BY COUNT(attacker) DESC
        );

或者如果您需要COUNT,您可以一起加入您的结果:

SELECT  tc.*, a.Dupe_cnt
FROM    [RohanGame].[dbo].[TCharacter]  tc
        INNER JOIN
        (   SELECT   TOP 15 attacker, COUNT(attacker) AS dupe_cnt 
            FROM [rohanstat].[dbo].[TPKill]
            GROUP BY attacker
            HAVING   COUNT(attacker) > 0
            ORDER BY COUNT(attacker) DESC
        ) a
            ON a.Attacker = tc.name;

如果有任何差异,我认为它不会产生太多影响,但你可以换掉:

HAVING   COUNT(attacker) > 0

WHERE   attacker IS NOT NULL

由于您已经被攻击者分组,因此COUNT(attacker)不为空的唯一组是攻击者为空的组:

SELECT  tc.*, a.Dupe_cnt
FROM    [RohanGame].[dbo].[TCharacter]  tc
        INNER JOIN
        (   SELECT   TOP 15 attacker, COUNT(*) AS dupe_cnt 
            FROM [rohanstat].[dbo].[TPKill]
            WHERE attacker IS NOT NULL
            GROUP BY attacker
            ORDER BY COUNT(*) DESC
        ) a
            ON a.Attacker = tc.name;

答案 1 :(得分:0)

问题的标签是SQL; SQL服务器

但mySQL Oracle和其他DB

相同

这里我回答T-SQL中的其他问题

您可以通过两种方式在PHP中完成 从DB1读取内存然后打开连接并将您的逻辑写入DB2

或在T-SQL中,您可以在一个查询中执行此操作

COPY data from table1 to table2 with date inserted as 7 days back or 14 days back?

答案 2 :(得分:0)

如果您想要使用PHP的解决方案,即您声明的$rows变量,您可以这样做:

$attackers = "";
foreach($rows as $row) {
  $attackers .= "$row,";
}
//Get rid of the last comma
$attackers = rtrim($attackers, ',');
$sql = sprintf("select * from [RohanGame].[dbo].[TCharacter] where name IN (%s)", $attackers);