1

我想过滤一个表格,但是在表格中有一个user_id列,我想过滤它的真实表格(我的意思是users.username)。

我的代码:

SELECT SQL_CALC_FOUND_ROWS `id`, `user_id`, `payment_type`, 
 `is_paid`, `is_invoiced`, `invoice_number`, `created_at`, `ip`,
 `data`, `coupon_code`, `payment_total`, 
 (select CONCAT(users.name,' ',users.surname) from users where users.id = orders.user_id) as fullname
FROM orders
WHERE (`fullname` LIKE '%M%' OR `payment_type` LIKE '%M%') ORDER BY `is_invoiced` asc

当我执行它时,会出现这样的错误:Unknown column 'fullname' in 'where clause'.

我该如何解决?

4

3 回答 3

2

您只能在 、 或 子句中使用GROUP BYORDER BY别名HAVING

来自 MySQL 文档:

标准 SQL 不允许您在 WHERE 子句中引用列别名。施加此限制是因为在执行 WHERE 代码时,可能尚未确定列值

参考:http ://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html

于 2013-06-16T11:19:03.780 回答
0

使用HAVING从句。

SELECT SQL_CALC_FOUND_ROWS id, user_id, payment_type, is_paid, 
is_invoiced, invoice_number, created_at, ip, data, coupon_code,
payment_total, (select CONCAT(users.name,' ',users.surname) 
from users where users.id = orders.user_id) as fullname 
FROM orders HAVING (fullname LIKE '%M%' OR payment_type LIKE '%M%') 
ORDER BY is_invoiced asc;
于 2013-06-16T11:40:57.930 回答
0

尝试使用CONCATinWHERE子句,例如:

SELECT SQL_CALC_FOUND_ROWS `id`, `user_id`, `payment_type`, 
`is_paid`, `is_invoiced`, `invoice_number`, `created_at`, `ip`,
`data`, `coupon_code`, `payment_total`, 
(select CONCAT(users.name,' ',users.surname) from users
WHERE CONCAT(users.name,' ',users.surname) LIKE '%M%'
and users.id = orders.user_id) as fullname
FROM orders
WHERE `payment_type` LIKE '%M%' ORDER BY `is_invoiced` asc
于 2013-06-16T11:57:32.713 回答