[英]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.