2016-11-25 147 views
0

我一直在搜索嵌套查询,但无法找到任何我可以掌握的关于如何去做这个特定操作的东西。查询关闭查询MYSQL

首先,我会告诉你我的DB模式

CREATE TABLE slsemp 
( empID char(4) NOT NULL, 
empname varchar(50) NOT NULL, 
prtime enum('yes','no') NOT NULL, # we can only accept yes or no values to the part-time employee indicator 
RegionID char(2) NOT NULL,    # enums are often used for boolean values in a BD 
PosID char(4) NOT NULL, 
PRIMARY KEY (empID), 
FOREIGN KEY (regionID) REFERENCES region (RegionID), 
FOREIGN KEY (PosID) REFERENCES slspos(PosID)); 


# create the sales transactions table 
CREATE TABLE slstranx 
( tranxID int(10) NOT NULL AUTO_INCREMENT, #starts at a certain number, then increments accordingly 
empID char(4) NOT NULL, 
ProdID char(3) NOT NULL, 
Qty int(5) NOT NULL, 
Unitprice Decimal(5,2) NOT NULL, # please note we are capturing the unit price at the transactional level in this case 
SAmt Float(10,2), #store up to 10 (TOTAL?) with 2 digits past decimal point 
SalesDate date, # 'date' data type is organized as follows YYYYMMDD. You need to make sure that raw data contains the DATE in the YYYYMMDD format 
       # For example 20150915 
PRIMARY KEY (tranxID), 
FOREIGN KEY (ProdID) REFERENCES product (ProdID), 
FOREIGN KEY (empID) REFERENCES slsemp (empID)); 

现在,我想找到那些在没有作出任何销售西部地区的员工。我想我会通过这两个表之间的左外连接来完成此操作,然后根据空tranx ID查询结果表。我知道了大部分的方式出现,这是我的查询:

SELECT e.empID, t.tranxID, e.RegionID 
FROM slsemp e LEFT OUTER JOIN slstranx t ON e.empID=t.empID 
WHERE e.RegionID='WS' 

我的问题是,如何查询基于这个结果表的标准。如果我能做到这一点,我只需要选择slstranxID = null的条件。

回答

1

您可以使用左连接加入其中slstranx.empID为空

select distinct empID, empName 
from slsemp 
left join slstranx on slsemp.empID = slstranx.empID 
where slsemp.RegionID = 'WS' 
and slstranx.empID is null 

如果从表中左连接柱是空意味着不匹配..所以没有销售

+0

我明白了。我以类似的方式得到了我的结果,除了我使用slstranx.tranxID为空。结果表是相同的。 我想最后的问题是:slstranx有什么区别。 是null和slstranx。 = null? –

+1

@ MadisonC.Brewer在sql中sintax some_column = null是错误的(sintax错误)你必须使用some_column为null,或者你可以用例如:ifnull(some_column,'')=''覆盖rhe null值。 ://dev.mysql.com/doc/refman/5.7/en/working-with-null.html – scaisEdge

+0

奇数,作为结果查询执行,它只是导致一个空表。好吧。现在我明白了。 –