更快的方式来实现代码mySQL子查询

时间:2013-07-15 19:36:56

标签: mysql performance subquery

我试图找到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;

1 个答案:

答案 0 :(得分:0)

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

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

    SELECT customer_id,COUNT(DISTINCT标题)   来自table_Y ty  INNER JOIN table_x tx ON tx.customer_id = ty.customer_id   有COUNT(DISTINCT ty.title)= 1   GROUP BY marital_status   ORDER BY tx.customer_id