2

所以我有3张桌子,

Companies (company_id, company_name)
Stock_Exchanges(stock_exchange_id, stock_exchange_name, stock_exchange_manager)
Stock_Exchanges_Companies(stock_exchange_id, company_id)

我正在尝试选择所有不在某个stock_exchange.

到目前为止我有这个:

SELECT COMPANY_NAME
  FROM COMPANIES c
  LEFT OUTER JOIN STOCK_EXCHANGES_COMPANIES sec 
    ON c.COMPANY_ID = sec.COMPANY_ID
  LEFT OUTER JOIN STOCK_EXCHANGES se 
    ON sec.STOCK_EXCHANGE_ID = se.STOCK_EXCHANGE_ID
 WHERE sec.COMPANY_ID != se.COMPANY_ID;

但是,当我使用该WHERE子句时,它返回零行。任何帮助,将不胜感激!

4

2 回答 2

2

嘿伙计们,我设法解决了这个问题!

我添加了一个额外的 AND 子句:

SELECT COMPANY_NAME
FROM COMPANIES c
LEFT OUTER JOIN STOCK_EXCHANGES_COMPANIES sec ON c.COMPANY_ID = sec.COMPANY_ID
LEFT OUTER JOIN STOCK_EXCHANGES se ON sec.STOCK_EXCHANGE_ID = se.STOCK_EXCHANGE_ID
WHERE sec.COMPANY_ID != se.COMPANY_ID
    AND sec.stock_exchange_id != idhere;
于 2013-08-20T11:45:03.857 回答
1

您根据匹配的 stockExchangeID 连接表,然后过滤到没有匹配的 stockExchangeID 的行,这就是您没有得到任何行的原因。是的,它们是左连接,所以如果没有匹配,你会从右连接部分得到空值,但这样设置似乎违反直觉。

假设您希望所有没有您特定 stock_exchange 的公司(包括没有证券交易所的公司),失去第一个 where 条件并执行以下操作:

SELECT COMPANY_NAME
FROM COMPANIES c
LEFT OUTER JOIN STOCK_EXCHANGES_COMPANIES sec 
    ON c.COMPANY_ID = sec.COMPANY_ID
LEFT OUTER JOIN STOCK_EXCHANGES se 
    ON sec.STOCK_EXCHANGE_ID = se.STOCK_EXCHANGE_ID
WHERE se.STOCK_EXCHANGE_ID != [idhere];

要选择有证券交易所但没有特定证券交易所的公司,请添加一个条件以检查它是否已加入 STOCK_EXCHANGES

SELECT COMPANY_NAME
FROM COMPANIES c
LEFT OUTER JOIN STOCK_EXCHANGES_COMPANIES sec 
    ON c.COMPANY_ID = sec.COMPANY_ID
LEFT OUTER JOIN STOCK_EXCHANGES se 
    ON sec.STOCK_EXCHANGE_ID = se.STOCK_EXCHANGE_ID
WHERE se.STOCK_EXCHANGE_ID != [idhere]
    AND se.STOCK_EXCHANGE_ID IS NOT NULL;
于 2013-08-20T14:59:10.717 回答