所以我有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
子句时,它返回零行。任何帮助将不胜感激!
答案 0 :(得分: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;
答案 1 :(得分:1)
您根据匹配的stockExchangeID加入表,然后过滤到没有匹配stockExchangeID的行,这就是没有行的原因。是的,它们是连接的,所以如果没有匹配的话,你会从连接的正确部分得到空值,但是设置它似乎是违反直觉的。
假设您想要所有没有特定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 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;