从多列创建数据集并将其与另一个数据集进行比较

时间:2012-11-24 09:07:57

标签: php mysql database compare

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

table_1包含3列a_ida_zonea_address

table_2包含4列p_idnot_usep_zonep_address

2个表中的行号不相同。我需要将table_1中的(a_zonea_address)的“数据集”与来自p_zone的(p_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仅与p_zone进行比较,或仅将a_address仅与p_address进行比较。相反,我需要比较整个数据组合。对于上面的示例,我需要将18与18 [a_zonea_addressp_zonep_address]进行比较

我坚持下去,真的需要帮助。请建议我.... :)

3 个答案:

答案 0 :(得分: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;
        }
    }
}

答案 1 :(得分: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

但这取决于你如何比较表格。

答案 2 :(得分: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);

返回:

enter image description here