简体   繁体   中英

How to check id of one table to another table?

How to find whether distinct value id of one table exits to another tables or not using php.

For example: Let table1 have id (not primary or unique) 4 , 5 , 6 , 4 , 6 , how to check if id of table2 have 4 , 5 , 6 or not ?

$query_check= "select distinct(project_code) from table1";
$projects_check = mysql_query($query_check);

while ($result_check = mysql_fetch_array($projects_check)){
    $all[] = $result_check[0];  
}

$query = "select id from table2";
$projects = mysql_query($query);
while ($result = mysql_fetch_array($projects)){
    foreach($all as $all_val){
        $pro_code = $result[0];
        if($pro_code != $all_val){ }
    }
}

This SQL may help:

SELECT table2.id 
FROM table2
WHERE table2.id NOT IN (
    SELECT DISTINCT table1.id
    FROM table1
)
SELECT table2.id 
FROM table2
WHERE table2.id IN (
    SELECT DISTINCT table1.id
    FROM table1
)

To get a list of all the project codes from table1 that are ids in table2:-

SELECT DISTINCT table1.project_code  
FROM table1
INNER JOIN table2
ON table1.project_code = table2.id

To get a list of all the project codes from table1 that are NOT ids in table2

SELECT DISTINCT table1.project_code  
FROM table1
LEFT OUTER JOIN table2
ON table1.project_code = table2.id
WHERE table2.id IS NULL

If it is the entries on 2 that you want that are not on 1

SELECT DISTINCT table2.id  
FROM table2
LEFT OUTER JOIN table1
ON table1.project_code = table2.id
WHERE table1.project_code IS NULL

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