SQL Select语句问题,如何解决

时间:2013-12-06 15:27:15

标签: sql join

我有2张桌子。它们被称为BB_CONTACTBB_PHONE

  • BB_CONTACTname(主键)和phone
  • BB_PHONEnamephonereplacement(真或假)

我需要进行查询,仅列出需要更换手机的BB_CONTACT人。

SELECT 
    BB_CONTACT.CONTACTNAME, 
from 
    BB_CONTACT, BB_PHONE
WHERE
    BB_PHONE.CONTACTNAME = BB_CONTACT.CONTACTNAME

上面的查询显示了BB_CONTACTBB_PHONE表中的联系人。但是,我需要创建一个SQL select语句来检查BB_CONTACT中的人是以下之一:

  • BB_PHONE.REPLACEMENT ='TRUE'且BB_CONTACT.PHONENUMBER不为空或
  • BB_PHONE.REPLACEMENT ='TRUE'且BB_CONTACT.PHONENUMBER为空或
  • BB_PHONE.REPLACEMENT ='FALSE'且BB_CONTACT.PHONENUMBER为空;

我不想包含符合以下条件的人:

BB_PHONE.REPLACEMENT = false AND BB_CONTACT.PHONENUMBER IS NOT NULL;

很抱歉,如果这看起来很简单,我就被困住了。我正在使用JDBC。

3 个答案:

答案 0 :(得分:1)

我确实相信这就是你所追求的目标:

SELECT C.CONTACTNAME
FROM BB_CONTACT AS C
  JOIN BB_PHONE AS P 
  ON C.CONTACTNAME = P.CONTACTNAME
WHERE 
  (
    P.REPLACEMENT = 'TRUE' OR
    (P.REPLACEMENT = 'FALSE' AND C.PHONENUMBER IS NULL)
  )

我简化了WHERE条件。

答案 1 :(得分:0)

你快到了......试试这个:

SELECT BB_CONTACT.CONTACTNAME, 
from BB_CONTACT JOIN BB_PHONE ON BB_PHONE.CONTACTNAME = BB_CONTACT.CONTACTNAME
WHERE 
(
  (BB_PHONE.REPLACEMENT = 'TRUE' AND BB_CONTACT.PHONENUMBER IS NOT NULL) OR
  (BB_PHONE.REPLACEMENT = 'TRUE' AND BB_CONTACT.PHONENUMBER IS NULL) OR
  (BB_PHONE.REPLACEMENT = 'FALSE' AND BB_CONTACT.PHONENUMBER IS NULL)
) 

答案 2 :(得分:0)

你自己回答了这个问题,只是将声明放在一起,结果将是这样的

SELECT BB_CONTACT.CONTACTNAME, 
FROM BB_CONTACT
INNER JOIN BB_PHONE ON BB_PHONE.CONTACTNAME = BB_CONTACT.CONTACTNAME
WHERE
(
  BB_PHONE.REPLACEMENT = 'TRUE' AND BB_CONTACT.PHONENUMBER IS NOT NULL OR
  BB_PHONE.REPLACEMENT = 'TRUE' AND BB_CONTACT.PHONENUMBER IS NULL OR
  BB_PHONE.REPLACEMENT = 'FALSE' AND BB_CONTACT.PHONENUMBER IS NULL
)
AND
(
  BB_PHONE.REPLACEMENT = 'FALSE' AND BB_CONTACT.PHONENUMBER IS NOT NULL
);

有更优雅的方法来解决您的问题,但应该这样做。