有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'
答案 0 :(得分:0)
如果它不是您的数据库列,则不能使用
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%'