如何检索表中具有不是最多次出现的值的行?

时间:2017-09-13 23:04:11

标签: mysql apache

我有两张桌子。

customers表和orders表。

customers:                          orders:
customer_id      customer_name      orders_id   customer_id
1111             Charles            1020        1111
2222             Bertram            1021        1111
3333             Barbare            1022        2222
                                    1023        3333

我希望输出为:

customer_name
Bertram
Barbara

我只想从BertramBarbara检索订单,因为他们没有下订单的次数最多。

这里的问题是子查询。我知道如何计算客户下订单的次数,但我在选择customer_id时出现的次数确实很困难。

使用mySQL和Apache

4 个答案:

答案 0 :(得分:0)

根据您的示例数据,您可能只找到1个订单的客户,您可以使用以下查询

SELECT customer_name
  FROM customer c
  JOIN orders o
    ON c.customer_id = o.customer_id
 GROUP BY customer_name
HAVING COUNT(orders_id) = 1

结果

customer_name
Bertram
Barbara

答案 1 :(得分:0)

由于您没有指定您正在使用的数据库,我假设您遇到标准SQL(分析函数不可用)。然后你可以依赖ALL运算符:

WITH count_table AS (SELECT customer_id, COUNT(*) AS num_of_orders
                     FROM your_table
                     GROUP BY customer_id)
SELECT *
FROM count_table
WHERE num_of_orders <= ALL(SELECT num_of_orders FROM count_table)

答案 2 :(得分:0)

我会将rank()用于此目的:

select oc.*
from (select o.customer_id, count(*) as cnt,
             rank() over (order by count(*) asc) as seqnum
      from orders o
      group by o.customer_id
     ) oc
where seqnum = 1;

这不会返回名称。但获得名称是一个简单的连接。

答案 3 :(得分:0)

我终于解决了!

    SELECT c.customer_id COUNT(o.order_id) "Orders"
    FROM orders o 
    INNER JOIN customers c 
    ON (o.customer_id = c.customer_id)
    GROUP BY o.customer_id
    HAVING Orders < ANY 
                        (SELECT COUNT(ord.customer_id)
                         FROM orders ord
                         GROUP BY ord.customer_id)