简体   繁体   中英

PHP MYSQL Join and output unmatched results

I've two tables : One called "Collected_items" and the Other "Wrong_Collected"..As shown below :

**collected_items**
item_no qty
x1       10
x2       20
BB       5
Z1       20
x13      13


**wrong_collected**
item_no qty
x1      10
x2      20
x13     13

As you can see, there are item no.'s occurred on both tables, but all i want is to output the one's which are not found in wrong_collected table.

$sql = mysql_query("SELECT collected_items.item_no,wrong_collected.item_no FROM collected_items, wrong_collected WHERE collected_items.item_no!=wrong_collected.item_no");
while($data = mysql_fetch_array($sql)){
   echo $data["item_no"];
}

The output shows all item no.'s except BB and Z1 ..Althout if you remove the ! from collected_items.item_no=wrong_collected.item_no the output will show the matching item_no's as follows :

X1 X2 X13

Sorry, I'm not really familiar with PHP. I've learned JOIN, but i never saw an example on how to output the unmatched results. Please Help !

change this:

SELECT collected_items.item_no,wrong_collected.item_no FROM collected_items, wrong_collected WHERE collected_items.item_no!=wrong_collected.item_no

to:

SELECT ci.item_no FROM collected_items ci 
left join wrong_collected wc on ci.item_no=wc.item_no 
WHERE wc.item_no is null;

使用此查询:

 select * from collected_items ci where not exists (select 1 from wrong_collected wc where ci.item_no = wc.item_no)

Here is the subquery example which gives the unmatched results

SELECT item_no FROM collected_items WHERE item_no  NOT IN 
(SELECT item_no  FROM  wrong_collected)

Hope it makes sense

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