0

我在数据库中有 2 个表:table_1table_2.

table_1包含 3 列即a_id, a_zone,a_address

table_2包含 4 列,即p_id, not_use, p_zone,p_address

两个表中的行号不同。我需要将来自 table_1 的 ( a_zone, )的“数据集”与来自 的 ( , ) 进行比较。a_addressp_zonep_addresstable_2

让我给你举个例子:

Table1 contains:

a_zone  a_address
=================
1       8
2       9
3       6
4       9
5       2

Table2 contains:

p_zone  p_address
=================
1       8
2       9
3       6
4       9
5       8

现在我需要像这样比较 a_zone, a_address = p_zone, p_address 与否。

我不需要仅将 a_zone 与 onlyp_zone或仅a_address与 only进行比较p_address。相反,我需要比较整个数据组合。对于我上面的例子,我需要比较 18 和 18 [ a_zone, a_addressWITH p_zone, p_address]

我被它困住了,真的需要帮助。请建议我.... :)

4

3 回答 3

0

如果我理解正确,你不能像这样做两个嵌套的while循环:

$query1 = get a_zone and a_address from table_1;
$query2 = get p_zone and p_address from table_2;

while($row = mysql_fetch_array($query1)) {
    $a_zone = $row['a_zone'];
    $a_address = $row['a_address'];
    while($row = mysql_fetch_array($query2)) {
        if($a_zone == $row['p_zone'] && $a_address == $row['p_address']) {
            do_something;
        }
    }
}
于 2012-11-24T09:15:34.803 回答
0

您可以从这样的查询开始:

SELECT *
FROM table_1 left join table_2
     on table_1.a_zone = table_2.p_zone
        and table_1.a_address = table_2.p_address
UNION
SELECT *
FROM table_1 right join table_2
     on table_1.a_zone = table_2.p_zone
        and table_1.a_address = table_2.p_address

然后你可以添加一些条件,像这样:

SELECT *
FROM table_1 left join table_2
     on table_1.a_zone = table_2.p_zone
        and table_1.a_address = table_2.p_address
WHERE table_2.p_id is null or table_1.a_id <> table_2.p_id
UNION
SELECT *
FROM table_1 right join table_2
     on table_1.a_zone = table_2.p_zone
        and table_1.a_address = table_2.p_address
WHERE table_1.p_id is null or table_1.a_id <> table_2.p_id

但这取决于您需要如何比较表格。

于 2012-11-24T09:15:34.833 回答
0

您还没有指定要返回的数据,所以我假设了一个简单的连接。

除非我误解了您的查询,否则我认为您不需要联合我认为您可以通过单个联接来做到这一点:

SELECT *
 FROM table_1 JOIN table_2 
 WHERE (table_1.a_zone = table_2.p_zone) && (table_1.a_address = table_2.p_address);

这将返回:

在此处输入图像描述

于 2012-11-24T09:45:51.367 回答