PostgreSQL在Where条件下使用别名

时间:2016-09-30 10:56:20

标签: sql postgresql conditional-statements

如何将条件设置为last_order字段,其中最后一个订单是由max sql函数创建的自定义字段,并按用户分组ID:

SELECT "users"."id", "users"."name", "users"."email", "users"."type", "users"."created_at", MAX(TO_CHAR(order_details.created_at, 'YYYY-MM-dd HH24:MM')) AS last_order
FROM "users"
LEFT JOIN "order_details" on "order_details"."user_id" = "users"."id"
WHERE EXISTS (
    SELECT *
    FROM "roles"
    LEFT JOIN "role_users" on "roles"."id" = "role_users"."role_id"
    WHERE "role_users"."user_id" = "users"."id" and "slug" = 'member'
) AND "users"."status" in (0)
AND (LOWER(CAST("users"."id" as TEXT)) LIKE '%%'
OR LOWER(CAST("email" as TEXT)) LIKE '%%'
OR LOWER(CAST("last_order" as TEXT)) LIKE '%%'
OR LOWER(CAST("name" as TEXT)) LIKE '%%')
GROUP BY "users"."id"
ORDER BY "created_at" desc

我总是收到这个错误:

column "last_order" does not exist

如何使用last_order?我已经用正确的别名来解决它。

由datatables生成的查询,错误原因是我使用了datatables的搜索功能的别名,我的数据表代码如下所示:

columns: [
    { data: 'id', name: 'users.id', class: 'text-center', orderable: false },
    { data: 'email', name: 'email' },
    { data: 'last_order', name: 'last_order', class: 'text-center', orderable: true },
    { data: 'name', name: 'name' },
]

1 个答案:

答案 0 :(得分:4)

两个问题:

  • 您不能使用select子句中where中定义的列别名。
  • 您不能在where子句中使用聚合函数。

将条件移至having子句:

. . .
GROUP BY "users"."id"
HAVING LOWER(CAST(last_order as TEXT)) LIKE '%%'
ORDER BY "created_at" desc

我认为您的like模式实际上比'%%'更有趣。并且,您不应该使用like作为日期/时间列。只需对日期部分使用适当的相等/范围比较或比较。