如何解决这个mysql查询,其中where条件用作列的值?

问题描述 投票:0回答:1

我有两张桌子即。客户和estimate_size。

顾客

enter image description here

estimate_size

enter image description here

我想获得以下结果:

customers under $1000             23
customers between $1000-$10000   45
customers between $10000-25000   23

etc.

我正在使用以下SQL:

SELECT `e`.`estimate_type`, COUNT(*) AS 'Total Customers' FROM `customers` AS `c` INNER JOIN `estimate_size` AS `e` ON `c`.`customer_estimate` = `e`.`estimate_value` GROUP BY `e`.`estimate_value` ORDER BY `e`.`estimate_type` 

但是我得到了错误的结果:

£10,000-25,000    3071
£1000-10,000      3071
£25,000-50,000    3071
Over £50,000      3071
Under £1000       3071

这有什么不对?

mysql
1个回答
1
投票

有什么不对的是你不能把一个where子句存储在一个列的字符串中,然后期望数据库实现,并以某种方式应用它只是因为你已经说过“这里的这个数字(customer_estimate)等于那个那里的字符串(“customer_estimate> 50000”)“ - 它不是;这些价值永远不会相等

你需要做的是让你的估计表看起来像这样:

estimate_id, estimate_type,   min_value, max_value
1,           "under 1000",    0,         1000
2,           "1000 to 10000", 1001,      10000
3,           "over 10000",    10001,     9999999999

然后是一个如下所示的查询:

SELECT
  e.estimate_type,
  COUNT(*)
FROM
  customer c
  INNER JOIN
  estimate_size e
  ON 
    c.value BETWEEN e.min_value and e.max_value
GROUP BY
  e.estimate_type

如果你确实希望坚持使用现在的东西,那么你可能必须非常复杂/参与将字符串剪切/解析为最小/最大,这样你就可以像我这里一样使用查询 - 它不是值得(脆弱),我会改变桌子,让生活变得简单

© www.soinside.com 2019 - 2024. All rights reserved.