如何从子查询中获取两个值,以在sql的where子句中使用

时间:2019-04-08 01:32:32

标签: sql sql-server

我必须在where子句中使用两个值来测试从子查询获得的两个值是否相等。由于我正在处理现有应用程序,因此我希望将其保留为子查询。以下是我的查询。

SELECT 
    o.EMAIL_ADDRESS, c.FIRST_NAME, p.PARTY_ID
FROM 
    ORDER o WITH (NOLOCK) 
INNER JOIN  
    PARTY p WITH (NOLOCK) ON o.ORDER_ID = p.PARTY_ID 
INNER JOIN 
    CUSTOMER c WITH (NOLOCK) ON p.PARTY_ID = c.CUSTOMER_ID 
WHERE 
    (o.EMAIL_ADDRESS, c.CUSTOMER_ID) IN (SELECT EMAIL_ADDRESS, CUSTOMER_ID 
                                         FROM CUSTOMER_MASTER 
                                         WHERE insert_date > '01/02/2019')

我面临的问题是where子句中的第一个值o.EMAIL_ADDRESS引发以下错误:

  

在需要条件的上下文中指定的非布尔类型的表达式

当我在where子句中使用单个值时,它工作正常。

3 个答案:

答案 0 :(得分:2)

一种方法是使用EXISTS和相关的子查询。

SELECT o.EMAIL_ADDRESS, c.FIRST_NAME, p.PARTY_ID
FROM ORDER_HEADER oh  WITH (NOLOCK) 
INNER JOIN  PARTY p WITH (NOLOCK) ON o.ORDER_ID = p.PARTY_ID 
INNER JOIN CUSTOMER c WITH (NOLOCK) ON p.PARTY_ID = c.CUSTOMER_ID 
WHERE EXISTS(
    SELECT 1
    FROM CUSTOMER_MASTER AS cm
    WHERE cm.insert_date > '01/02/2019'
    AND o.EMAIL_ADDRESS = cm.EMAIL_ADDRESS
    AND c.CUSTOMER_ID = cm.c.CUSTOMER_ID
    );

答案 1 :(得分:0)

in仅允许单列列表。因此,创建单列。

SELECT o.EMAIL_ADDRESS, c.FIRST_NAME, p.PARTY_ID
FROM ORDER o  WITH (NOLOCK) 
INNER JOIN  PARTY p WITH (NOLOCK) ON o.ORDER_ID = p.PARTY_ID 
INNER JOIN CUSTOMER c WITH (NOLOCK) ON p.PARTY_ID = c.CUSTOMER_ID 
WHERE o.EMAIL_ADDRESS + cast(c.CUSTOMER_ID as varchar) 
IN (select EMAIL_ADDRESS + cast(CUSTOMER_ID as varchar)
from CUSTOMER_MASTER where insert_date > '01/02/2019')

答案 2 :(得分:0)

使用EXISTS。我也建议固定日期格式:

SELECT o.EMAIL_ADDRESS, c.FIRST_NAME, p.PARTY_ID
FROM ORDER o JOIN
     PARTY p 
     ON o.ORDER_ID = p.PARTY_ID JOIN
     CUSTOMER c 
     ON p.PARTY_ID = c.CUSTOMER_ID 
WHERE EXISTS (SELECT 1
              FROM CUSTOMER_MASTER cm
              WHERE cm.EMAIL_ADDRESS = o.EMAIL_ADDRESS AND
                    cm.CUSTOMER_ID = c.CUSTOMER_ID AND
                    cm.insert_date > '2019-02-01'
             );

您的日期常量应采用YYYYMMDD格式。

不过,根据您的逻辑,我认为您不需要所有的JOIN

SELECT o.EMAIL_ADDRESS, c.FIRST_NAME, o.ORDER_ID
FROM ORDER o JOIN
     CUSTOMER c 
     ON o.ORDER_ID = c.CUSTOMER_ID 
WHERE EXISTS (SELECT 1
              FROM CUSTOMER_MASTER cm
              WHERE cm.EMAIL_ADDRESS = o.EMAIL_ADDRESS AND
                    cm.CUSTOMER_ID = c.CUSTOMER_ID AND
                    cm.insert_date > '2019-02-01'
             );

PARTY表似乎没有必要,因为订单可以直接与客户对齐。