MySQL Query返回重复的结果

时间:2012-04-22 06:49:27

标签: mysql database

我是MySQL的新手,我正在使用一个数据库系统,它有四个主表,如下所述:

http://www.pastie.org/3832181

此查询主要使用的表位于:

http://www.pastie.org/3832184

看起来相当简单吧?

我的查询的目的是获取OpportunityID为NULL的显式用户的所有BusinessID,一旦它具有那些BusinessID,我希望它在Business表中找到关联的BusinessName并将该BusinessName与BusinessName(Business)匹配在EmploymentOpportunity表中。

这是我执行该操作的查询。

SELECT EmploymentOpportunity.OpportunityID, Business, Description 
FROM UserBusinessOpportunity, Business, EmploymentOpportunity
WHERE UserBusinessOpportunity.BusinessID = 
          (SELECT UserBusinessOpportunity.BusinessID 
          FROM UserBusinessOpportunity 
          WHERE UserBusinessOpportunity.UserID=1 AND
                UserBusinessOpportunity.OpportunityID is NULL) 
       AND UserBusinessOpportunity.BusinessID = Business.BusinessID 
       AND Business.BusinessName = EmploymentOpportunity.Business;

子选择语句应该返回BusinessID的子集。我确信这是一个非常简单的查询,但它一直给我重复的结果,我很确定为什么。结果集应该是3,但它发送给我24个,或者8个重复的那3个。

谢谢,如果你能帮我解决这个问题。

3 个答案:

答案 0 :(得分:2)

使用distinct关键字删除重复项。

看看here

答案 1 :(得分:1)

当您在SQL语句中进行连接时,可能会在某处丢失约束。根据我的描述,听起来这个查询可能对您有用。

SELECT 
    User.UserID,
    Business.BusinessID,
    Business.BusinessName
FROM
    User,
    UserBusinessOpportunity,
    Business
WHERE
    User.UserID = 1 AND
    User.UserID = UserBusinessOpportunity.UserID AND
    UserBusinessOpportunity.OpportunityID IS NULL AND
    UserBusinessOpportunity.BusinessID = Business.BusinessID 

答案 2 :(得分:1)

我认为您打算进行内连接,但您的查询是隐式外连接。

使用空字段连接通常最适合使用左连接。

试试这个:

SELECT EmploymentOpportunity.OpportunityID, Business, Description
FROM EmploymentOpportunity
JOIN Business ON Business.BusinessName = EmploymentOpportunity.Business
LEFT JOIN UserBusinessOpportunity USING(BusinessID) 
WHERE
 UserBusinessOpportunity.UserID=1
AND
 UserBusinessOpportunity.OpportunityID is NULL

儒略