繁体   English   中英

Php / MySql 从不同的表中找到重复的记录,并参考它们来自哪里

[英]Php / MySql find duplicated records from different tables and refer from where did they come from

我有 2 张桌子,“amigos”和“socios”。 在 amigos 我有行 id、nr_amigo、nome 在 socials 我有行 id、nr_socio、nome

如果有重复的记录,我需要在两个表中搜索

如果我使用

SELECT id, nr_amigo as amigo FROM amigos WHERE nome = :variavel
UNION
SELECT id, nr_socio as socio FROM socios WHERE nome = :variavel

它有效,但我无法从哪张桌子上知道找到的匹配已经到来

所以我的问题是我如何列出重复记录(如果有)以及我如何知道它们来自哪里?

在 php 我已经

$sql_pesquisar -> execute($dados_a_enviar);
$num_rows_query = $sql_pesquisar -> rowCount();
if ($num_rows_query > 0) {
    while($row = $sql_pesquisar -> fetch(PDO::FETCH_ASSOC)) {
        print_r($row);
    }
}

结果是

Array
(
    [id] => 180
    [nr_amigo] => 180
)

但事实上,该记录来自“socios”而不是“amigos”

谢谢!

您可以在tablename列表中添加一个新列作为表select来标识该表。 最终查询将像

SELECT id, 'amigos' as tablename, nr_amigo as amigo FROM amigos WHERE nome = :variavel
UNION
SELECT id, 'socios' as tablename, nr_socio as socio FROM socios WHERE nome = :variavel

然后,您可以使用 php 中的tablename列来确定记录属于哪个表。

除了他的回答中提到的@ascsoftw 之外,还有另一种选择。

您可以 select null 到您在当前子查询中未选择的列,如下所示

SELECT id, nr_amigo AS amigo, NULL as socio FROM amigos WHERE nome = :variavel
UNION ALL
SELECT id, NULL AS amigo, nr_socio AS socio FROM socios WHERE nome = :variavel

结果将如下所示

Array
(
    [id] => 180
    [amigo] => 180
    [socio] => null
)

或者

Array
(
    [id] => 180
    [amigo] => null
    [socio] => 180
)

如果要列出重复条目,请确保使用UNION ALL

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM