我想过滤一个表,但在表格中有一个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'
。
我该如何解决?
答案 0 :(得分:2)
您只能在GROUP BY
,ORDER BY
或HAVING
条款中使用列别名。
来自MySQL文档:
标准SQL不允许您引用WHERE中的列别名 条款。强制执行此限制是因为WHERE代码是 执行后,列值可能尚未确定
参考:http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html
答案 1 :(得分: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;
答案 2 :(得分:0)
尝试在CONCAT
子句中使用WHERE
,如:
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