简体   繁体   English

PHP MYSQL加入并输出不匹配的结果

[英]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”,另一个叫“ Wrong_Collected”。如下所示:

**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 ! 输出显示了所有项目没有。是除了BBZ1 ..Althout如果去掉! from collected_items.item_no=wrong_collected.item_no the output will show the matching item_no's as follows : collected_items.item_no=wrong_collected.item_no ,输出将显示匹配的item_no,如下所示:

X1 X2 X13

Sorry, I'm not really familiar with PHP. 抱歉,我对PHP不是很熟悉。 I've learned JOIN, but i never saw an example on how to output the unmatched results. 我已经学习了JOIN,但从未见过有关如何输出不匹配结果的示例。 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 这是给出不匹配结果的subquery示例

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

Hope it makes sense 希望有道理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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