[英]Php / MySql find duplicated records from different tables and refer from where did they come from
I've 2 tables, "amigos" and "socios".我有 2 张桌子,“amigos”和“socios”。 In amigos I've rows id, nr_amigo, nome In socios I've rows id, nr_socio, nome在 amigos 我有行 id、nr_amigo、nome 在 socials 我有行 id、nr_socio、nome
I need to search in both tables if there are duplicated records如果有重复的记录,我需要在两个表中搜索
If I use如果我使用
SELECT id, nr_amigo as amigo FROM amigos WHERE nome = :variavel
UNION
SELECT id, nr_socio as socio FROM socios WHERE nome = :variavel
It works, BUT I can't know from wich table the found match has come它有效,但我无法从哪张桌子上知道找到的匹配已经到来
So my question is how do I list duplicated records (if any) and How do I know where did they came from?所以我的问题是我如何列出重复记录(如果有)以及我如何知道它们来自哪里?
In php I've在 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);
}
}
Result is结果是
Array
(
[id] => 180
[nr_amigo] => 180
)
But in fact that record is from "socios" and not from "amigos"但事实上,该记录来自“socios”而不是“amigos”
Thanks!谢谢!
You can add a new column as tablename
in the select
list to identify the table.您可以在tablename
列表中添加一个新列作为表select
来标识该表。 Final query will be like最终查询将像
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
You can then identify using tablename
column in php to determine which table the record belongs to.然后,您可以使用 php 中的tablename
列来确定记录属于哪个表。
There is another option besides the one @ascsoftw mentioned in his answer.除了他的回答中提到的@ascsoftw 之外,还有另一种选择。
You can select null to the column you are not selecting in current subquery like this您可以 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
The result will then look like结果将如下所示
Array
(
[id] => 180
[amigo] => 180
[socio] => null
)
or或者
Array
(
[id] => 180
[amigo] => null
[socio] => 180
)
Make sure to use UNION ALL
if you want to list duplicate entries.如果要列出重复条目,请确保使用UNION ALL
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.