我将我的数据库中一些在流量方面有问题的表移动到另一台服务器并且不想使用 联合表出于很多原因(性能是主要原因)。所以我必须在我的 PHP 类中创建 2 个不同的连接 并在代码中重写我的查询,这些代码在来自不同服务器的表之间进行了连接。
例如,我有两个表:Users 和 Enterprise,它们位于不同的服务器上。
当它在同一台服务器上时,查询是:
select name from Enterprise E
inner join Users U on E.cod = U.cod
where E.cod = $my_code and U.codUsers in ($users);
所以我改成这样:
$rst= select group_concat(U.cod) from Users as U
where U.codUsers in ($users)
select name from Enterprise E
where E.cod = $mycode and E.cod in ($rst);
我的问题是,当我有这种类型的查询时,我怎样才能做到这一点:
select e.name, e.datebegin, e.dateend from Enterprise E
leftjoin ( select h.callQuantity, h.history from thirdtable
inner join Users u on e.cod = u.cod
where u.codHistory in (1,2,3)
group by u.cod)
我的问题清楚了吗?对不起我的英语
最佳答案
首先,联合表是更好的解决方案(它们正是为您尝试手动完成的那种事情而设计的)。但是您不想要它们,所以这是下一个最好的事情:
对于比您的第一个示例更复杂的任何事情,您应该通过插入表格内容而不是表格来手动模拟远程表格。
我将以这种方式重写你的第一个例子,因为你的第二个例子搞砸了,我什至不知道你想在那里表达什么。
您在使用 1 个服务器时有以下代码:
select name from Enterprise E
inner join Users U on E.cod = U.cod
where E.cod = $my_code and U.codUsers in ($users);
您现在可以用表格的实际数据替换表格:
select name from Enterprise E
inner join
( select 1 as cod, 4 as codUsers, 20 as codHistory
union select 2 as cod, 8 as codUsers, 500 as codHistory
union select 3 as cod, 29 as codUsers, 100 as codHistory
) as U
on E.cod = U.cod
where E.cod = $my_code and U.codUsers in ($users);
为此,您必须将表数据构建为字符串(我在这里使用 pdo):
foreach($db->query('select * from Users U where U.codUsers in ($users)') as $row) {
if($data !== '') { $data .= 'union '; }
$data .= 'select ' . $row['cod'] . ' as cod, '
. $row['codUsers'] . ' as codUsers, '
. $row['codHistory'] . ' as codHistory ';
}
当然,您必须使其适合您的用户表的布局(并且不要忘记一些 ' 用于字符串列),并且您可以省略不需要的列。
您现在可以将该字符串放在您之前拥有 Users 表的任何位置,并像在一台服务器上一样编写您的代码,因此您的第一个代码看起来像
select name from Enterprise E
inner join ($data) as U on E.cod = U.cod
where E.cod = $my_code and U.codUsers in ($users);
你的第二个代码(虽然我提醒你它一开始就坏了,也不能在一台服务器上工作)看起来像
select e.name, e.datebegin, e.dateend from Enterprise E
leftjoin ( select h.callQuantity, h.history from thirdtable
inner join ($data) as u on e.cod = u.cod
where u.codHistory in (1,2,3)
group by u.cod)
您应该确保只有少量用户进入您的 $data-string,这样就可以正常工作。否则,您真的需要联合表。
关于php - 不使用联合表的Mysql跨服务器查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36747861/