在子查询中使用count

时间:2019-05-05 07:15:03

标签: mysql

我目前正在学习mysql中的子查询,只想弄清楚im是否在正确的轨道上。下面的代码确实带来了结果,但是不确定是否正确执行了。问题是

“使用IN语句查找在1997年4月提交了至少一份订单的所有客户的代码和公司名称。”

    uglifyOptions: {
          compress: {
                warnings: false,
                pure_funcs: ['console.log']
          }
    }

我仔细检查了插入表中的值,即使产生了结果,它似乎也不正确。

(注意,使用EXIST子句与IN子句相同,但不是WHERE CUSTOMER_CODE IN而是WHERE EXISTS吗?

我尝试过

SELECT CUSTOMER_CODE, COMPANY_NAME
FROM CUSTOMER
WHERE CUSTOMER_CODE IN (SELECT CUSTOMER_CODE
     FROM ORDERS
        WHERE ORDER_DATE BETWEEN  '1997-04-01' AND '1997-04-30'
        GROUP BY CUSTOMER_CODE )

这是我正在使用的两个标签

SELECT CUSTOMER_CODE, COMPANY_NAME
FROM CUSTOMER
WHERE NOT EXISTS (SELECT CUSTOMER_CODE
     FROM ORDERS
        WHERE ORDER_DATE BETWEEN  '1997-04-01' AND '1997-04-30'
        GROUP BY CUSTOMER_CODE );  
CREATE TABLE CUSTOMER
(
    CUSTOMER_CODE   VARCHAR(5)  NOT NULL,
    COMPANY_NAME    VARCHAR(40) NOT NULL,
    CONTACT_NAME    VARCHAR(30),
    CONTACT_TITLE   VARCHAR(30),
    ADDRESS         VARCHAR(60),
    CITY        VARCHAR(15),
    REGION      VARCHAR(15),
    POSTAL_CODE     VARCHAR(10),
    COUNTRY         VARCHAR(15),
    PHONE       VARCHAR(24),
    FAX         VARCHAR(24),
    CONSTRAINT PK_CUSTOMER PRIMARY KEY (CUSTOMER_CODE)
);

但我收到一个空集 谢谢大家的时间

2 个答案:

答案 0 :(得分:1)

代替IN子句,您可以基于同一子查询使用INNER JOIN ..

通常比In子句

效果更好
  SELECT CUSTOMER_CODE, COMPANY_NAME
  FROM CUSTOMER
  INNER JOIN (
      SELECT DISTINCT CUSTOMER_CODE
      FROM ORDERS
      WHERE ORDER_DATE BETWEEN  '1997-04-01' AND '1997-04-30'
  ) t on t.CUSTOMER_CODE = CUSTOMER.CUSTOMER_CODE 

当您不使用聚合功能时,您不应使用group by for(默认情况下,在最新版本的mysql中这无效) 如果只需要不同的结果,请使用DISTINCT

答案 1 :(得分:1)

您必须使用EXISTS而不是NOT EXISTS:

SELECT c.CUSTOMER_CODE, c.COMPANY_NAME
FROM CUSTOMER c
WHERE EXISTS (
  SELECT CUSTOMER_CODE FROM ORDERS
  WHERE 
  CUSTOMER_CODE = c.CUSTOMER_CODE
  AND
  ORDER_DATE BETWEEN '1997-04-01' AND '1997-04-30'
);

您还可以通过以下方法查看ORDER_DATE

YEAR(ORDER_DATE) = 1997 AND MONTH(ORDER_DATE) = 4 

您也可以使用IN:

SELECT CUSTOMER_CODE, COMPANY_NAME
FROM CUSTOMER
WHERE CUSTOMER_CODE IN (
  SELECT CUSTOMER_CODE FROM ORDERS
  WHERE YEAR(ORDER_DATE) = 1997 AND MONTH(ORDER_DATE) = 4 
);

如果要查找未提交订单的所有客户总数

SELECT COUNT(DISTINCT c.CUSTOMER_CODE) AS COUNTER
FROM CUSTOMER c
WHERE NOT EXISTS (
  SELECT CUSTOMER_CODE FROM ORDERS
  WHERE CUSTOMER_CODE = c.CUSTOMER_CODE
)