SQL查询帮助 - 在连接条件中有两个条件

时间:2011-07-18 12:02:36

标签: mysql sql sql-server

我有这些表 - 书(b),贸易(t),TradingDesk(d),CounterParty(c)。

Trade(t)有2列买方,卖方看起来像

**Buyer** **Seller**
B456  B222 
C55   B222 
B323  C4333

我必须根据买方和卖方列中的值加入书(b)。即,如果值以'B'开头,则应检查Books表中是否存在该ID,例如:对于B456 - 应使用Books表检查id 456。

我写了以下内容可以做到这一点:

SELECT DISTINCT d.Name, t.Buyer, t.Seller FROM  Book AS b
  INNER JOIN TradingDesk AS d  ON b.TradingDeskId = d.Id
    Join Trade as t 
       on  substring(t.Seller,2,len(t.Seller)) = cast(b.Id as varchar)
UNION
SELECT DISTINCT d.Name , t.Buyer, t.Seller FROM  Book AS b 
  INNER JOIN TradingDesk AS d ON b.TradingDeskId = d.Id
    Join Trade as t 
       on substring(t.Buyer,2,len(t.Buyer)) = cast(b.Id as varchar)

现在,我需要使用CounterParty(c)表检查以'C'开头的值。我尝试在连接中添加where条件,但这不起作用并在where语句中给出错误。 我尝试用条件调整连接条件:

on  substring(t.Seller,2,len(t.Seller)) = cast(b.Id as varchar) where t.Seller like 'B%' 
 AND
substring(t.Seller,2,len(t.Seller)) = cast(c.partyId as varchar) where t.Seller like 'C%'

但似乎我不能在ON部分设置两个条件,其中多个条件。

实现这一目标的任何方式?

由于 摩尼

3 个答案:

答案 0 :(得分:0)

将其转换为LEFT JOIN,然后将附加条件放在那里

SELECT DISTINCT d.Name, t.Buyer, t.Seller FROM  Book AS b
  LEFT JOIN TradingDesk AS d  ON b.TradingDeskId = d.Id
    LEFT Join Trade as t 
       on  substring(t.Seller,2,len(t.Seller)) = cast(b.Id as varchar)

       AND t.Seller like 'B%' -- put your additional condition(s) here

UNION
SELECT DISTINCT d.Name , t.Buyer, t.Seller FROM  Book AS b 
  LEFT JOIN TradingDesk AS d ON b.TradingDeskId = d.Id
    LEFT Join Trade as t 
       on substring(t.Buyer,2,len(t.Buyer)) = cast(b.Id as varchar)

答案 1 :(得分:0)

以下查询很可能是次优的,但它应该为您提供必要的结果,因此,至少为您提供一个起点:

SELECT
  d.Name,
  t.Buyer,
  t.Seller
FROM (
  SELECT
    'B' AS Prefix,
    COUNT(Id AS varchar(20)) AS Id,
    TradingDeskId
  FROM Book
  UNION ALL
  SELECT
    'C' AS Prefix,
    COUNT(Id AS varchar(20)) AS Id,
    TradingDeskId
  FROM CounterParty
) bc
  INNER JOIN TradingDesk d ON d.Id = bc.TradingDeskId
  INNER JOIN Trade t ON bc.Prefix + bc.Id IN (t.Buyer, t.Seller)

答案 2 :(得分:0)

你可以这样做(未经测试):

select 
  t.Buyer, 
  t.Seller, 
  case when t.Buyer like 'B%' THEN (select BookName from Book where BookId = t.Buyer)
                              ELSE (select CpName from Counterparty where CPId = t.Buyer)
  end BuyerName,
  case when t.Seller like 'B%' THEN (select BookName from Book where BookId = t.Seller)
                               ELSE (select CpName from Counterparty where CPId = t.Seller)
  end SellerName
from 
  Trade t

您遇到的问题是,由于您要加入的表是数据驱动的,因此您无法在FROM子句中指定它。