查询查询MYSQL

时间:2016-11-25 19:00:09

标签: mysql

我一直在搜索有关嵌套查询的信息,但却无法找到关于如何进行此特定操作的任何内容。

首先,我将向您展示我的数据库架构

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));

现在,我想找到西部地区没有销售的员工。我想我会通过两个表之间的左外连接来执行此操作,然后根据null tr​​anx 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 个答案:

答案 0 :(得分: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 

如果左连接表中的列为空则表示不匹配..所以没有销售