简体   繁体   中英

compare two tables with same column for similar values

I have two tables tableA and tableB . Both have two similar columns ID and B_ID . I want to check whether both table have similar values. My code is:

$ac = $mysql->query("(SELECT ID,B_ID FROM tableA) INTERSECT (SELECT ID,B_ID FROM tableB)");

  if($ac){
    while($row  = $ac->fetch_assoc()){

      echo "ID ".$row["ID"]." B_ID".$row["B_ID"]."<br>";
    }
  }

But this doesn't give any result.

    ps: tableA(ID,B_ID)

 1->23
 2->23
 3->23
 4->56
 5->67

tableB(ID,B_ID)

3->23
8->26
11->27
12->66

here both table has 3->23 but 1->23 2->23 is not in tableB how can i figure that sort of records. same B_ID but different ID

If you have B.ID column is present in both table then use following JOIN query

SELECT a.ID, a.B_ID 
FROM tableA AS a
JOIN tableB AS b ON (a.B_ID = b.B_ID AND a.ID = b.ID)

Use a join to get the data and just iterate over your results. Run the query and if there is any record that satisfies the query or not.

select t1.ID, t1.B_ID from tableA t1, tableB t2
where t1.ID = t2.ID
and   t1.B_ID =t2.B_ID  

Use an INNER JOIN and COUNT

SELECT COUNT(*) as cnt
FROM tableA INNER JOIN tableB
ON tableA.B_ID = tableB.B_ID AND tableA.ID = tableB.ID

now if cnt is greater than zero than common values exist, otherwise no

Please try with this query may be help full.

SELECT
    tbla.ID,
    tbla.B_ID
FROM
    tablea AS tbla,
    tableb AS tblb
WHERE
    tbla.B_ID = tblb.B_ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM