首页 > 解决方案 > 两表比较和列出php

问题描述

有两个不同的表。我想在这两个表中的同名列中找到带有“%USD”的表达式不匹配并在屏幕上列出它们。

表1查询;

<?php
include("db.php");
$queb = $conn->query("select distinct symbol from tableA WHERE symbol LIKE '%USD'"); 
while ($resb = $queb->fetch_assoc()){
$symbolb = $resb['symbol'];
}

?>

表2查询;

<?php
include("db.php");
$quec = $conn->query("select distinct symbol from tableB WHERE symbol LIKE '%USD'"); 
while ($resc = $quec->fetch_assoc()){
$symbolc = $resc['symbol'];

}
?>

如何列出不在两个表之间的表达式?

标签: phpmysql

解决方案


我可能没有完全理解你的问题。如果您想列出以 'USD' 开头的 intableA但不在 intableB的符号以及以not intableB开头的符号,则以下查询应返回这些符号:USDtableA

select distinct symbol from tableA
    where symbol LIKE '%USD' and symbol not in (select distinct symbol from tableB)
union
select distinct symbol from tableB
    where symbol LIKE '%USD' and symbol not in (select distinct symbol from tableA)

或者您可以改用外部联接:

select distinct symbol from tableA left join tableB on tableA.symbol = tableB.symbol
    where tableA.symbol like ('%USD') and tableB.symbol is null
union
select distinct symbol from tableB left join tableA on tableB.symbol = tableA.symbol
    where tableB.symbol like ('%USD') and tableA.symbol is null

在任何一种情况下,如果您在symbol列上有索引,性能都会得到提高。


推荐阅读