【问题标题】:How to filter rows with orders of special product? [duplicate]如何过滤特殊产品订单的行? [复制]
【发布时间】:2019-05-02 08:41:43
【问题描述】:

customer表:

---+-------+------------+
id + name  + region     + 
---+-------+------------+

还有orders表:

---+--------------+------------+----------+----------------+
id + cusomer_id   + product    +  price   +  amount_total  +
---+--------------+------------+----------+----------------+

如果我想形成一个每个客户都购买过的产品列表,用“;”表示,我提出一个要求:

            SELECT GROUP_CONCAT(orders.product separator ';') 
            FROM orders
            WHERE orders.customer_id = customer.id

一切正常,但是如果我想添加一些过滤器,则会出现错误:

SELECT customers.id, 
      (SELECT GROUP_CONCAT(orders.product separator ';') 
       FROM orders
       WHERE orders.customer_id = customers.id) as products 
FROM  customers        
WHERE customers.region like 'USA' 
      AND products not like '%fish%'


Query Error: Error: ER_BAD_FIELD_ERROR: Unknown column 'products' in 'where clause'

db-fiddle.com

【问题讨论】:

  • 如果products 不是您的数据库列,则不能使用
  • 只能在 MySQL 的 HAVING 子句中使用别名。将AND products not like '%fish%' 更改为HAVING products not like '%fish%'
  • @vppy 不用担心 - 如果我作为骗子关闭,我总是会尝试提供解决方案......
  • @Nick 谢谢!真正支持的方法。祝你在所有项目中好运。干杯!

标签: mysql sql


【解决方案1】:

如果不是您的数据库列,您不能使用products,您需要这样做才能完成它

SELECT customers.id, 
      (SELECT GROUP_CONCAT(orders.product separator ';') 
       FROM orders
       WHERE orders.customer_id = customers.id) as products 
FROM  customers        
WHERE customers.region like 'USA' 
      AND (SELECT GROUP_CONCAT(orders.product separator ';') 
       FROM orders
       WHERE orders.customer_id = customers.id) not like '%fish%'

【讨论】:

  • 成功了,谢谢支持。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-26
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
相关资源
最近更新 更多