简体   繁体   English

MYSQL NOT IN子选择

[英]MYSQL NOT IN subselect

I have two table 我有两个桌子

  1. item
  2. confirmmasterdetail

I want to select records from item table whose is not in confirmmasterdetail table when me run this query at that it's return empty result set. 我要从项目表中选择记录,而当我运行该查询时,它返回的结果集为空,而该表不在confirmmasterdetail表中。

SELECT itemId
,      itemName
FROM   item
LEFT 
JOIN   item /* HERE AN ALIAS IS MISSING, ITEM occurs twice. */
ON     item.itemId = confirmmasterdetail.itemId
WHERE  confirmmasterdetail.itemId 
       NOT IN 
       ( SELECT confirmmasterdetail.itemId
         FROM   confirmmasterdetail
       )
AND    confirmMasterId = ".$_REQUEST['confirmMasterId'];

See your query. 查看您的查询。 Please prefix all columns selected with either table name or (better) add an alias to each table and use that one. 请为所有选择的列添加表名或(更好)作为前缀,并为每个表添加别名并使用该表。 Also note that item occurs twice in the query, so column names might not be what they seem to be. 还要注意,该item在查询中出现两次,因此列名可能看起来不正确。

Finally, ensure null can not be returned from the subselect. 最后,确保不能从子选择中返回null

I believe your query has basic conceptual problems with SQL. 我相信您的查询在SQL中存在基本的概念性问题。 It is hard to give advice without a clear statement of what you want and how the tables look like. 如果没有清楚说明所需内容以及表的外观,就很难给出建议。 To help you, we need at least information about the tables (what columns and how are they connected). 为了帮助您,我们至少需要有关表的信息(哪些列以及它们如何连接)。

Edit : With the information you provided you might want to try one of these queries: 编辑 :根据您提供的信息,您可能需要尝试以下查询之一:

  1. Select all items that have no corresponding entry in confirmmasterdetail: 选择所有在confirmmasterdetail中没有相应条目的项目:

     SELECT itemId , itemName FROM item WHERE item.itemId NOT IN ( SELECT confirmmasterdetail.itemId FROM confirmmasterdetail ); 
  2. Select all items that have no entry in confirmmasterdetail with the given confirmMasterId: 使用给定的confirmMasterId选择在confirmmasterdetail中没有条目的所有项目:

     SELECT itemId , itemName FROM item WHERE item.itemId NOT IN ( SELECT confirmmasterdetail.itemId FROM confirmmasterdetail WHERE confirmMasterId = ".$_REQUEST['confirmMasterId'] ); 

There is one important thing about null in SQL, it means unknown not nothing . SQL中关于null一件重要事情是,它意味着unknown而不是nothing So if your sub-query returns null values, it means unknown , and not in unknown makes DBMS to ignore all records. 因此,如果您的子查询返回null值,则意味着unknown ,而not in unknown使DBMS忽略所有记录。

Just change the subquery to: 只需将子查询更改为:

SELECT confirmmasterdetail.itemId
  FROM confirmmasterdetail
 WHERE confirmmasterdetail.itemId is not null

Try this query - 试试这个查询-

SELECT
  i.*
FROM item i
  LEFT JOIN confirmmasterdetail c
    ON i.itemId = c.itemId
WHERE
  c.itemId IS NULL

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

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