1

我试图在 table_Y 中找到拥有不同数量标题的客户总数,并将它们按 table_X 中的 marital_status 分组。我无法加入他们,因为我没有加入他们的唯一密钥。我正在编写以下 mySQL 脚本,该脚本需要很长时间。有没有更好的方法来写这个?谢谢:

 SELECT COUNT(DISTINCT customer_id), marital_status FROM table_X
    WHERE customer_id IN (
    SELECT COUNT(DISTINCT customer_id)
    FROM
    (
    SELECT customer_id,COUNT(DISTINCT title) 
    FROM table_Y
    GROUP BY customer_id 
    HAVING COUNT(DISTINCT title)=1
    ORDER BY customer_id) as t1)
    GROUP BY marital_status;
4

1 回答 1

0
  1. 即使您的查询似乎有效,我几乎可以肯定它不会返回您想要的结果,主要是因为WHERE customer_id IN ( SELECT COUNT(DISTINCT customer_id) .... customer_id应该与业务相关的值无关。

  2. 似乎您可以进行联接,因为您的两个表都包含customer_id列,这可能代表相同的事物,因此您可以这样做:

    SELECT customer_id,COUNT(DISTINCT title) FROM table_Y ty INNER JOIN table_x tx ON tx.customer_id = ty.customer_id HAVING COUNT(DISTINCT ty.title)=1 GROUP BY marital_status ORDER BY tx.customer_id

于 2013-07-15T19:49:53.963 回答