[英]Can I alias a column with an AS in the SELECT part of a MySQL query?
Ive got a rather complicated query Im running, and before I change a table structure and rewrite some other files I was wondering if anyone could tell me if this is possible. 我正在运行一个相当复杂的查询,在更改表结构并重写其他文件之前,我想知道是否有人可以告诉我是否可行。
SELECT
DISTINCT(users.user_id),
(resi.curr_state WHERE resi.user_id = "users.user_id") AS current_state
FROM
ci_users AS users, ci_residents AS resi .....
WHERE stuff HAVING current_state = '".$php_variable_ill_use."'
Im happy to share more code if necessary, but my main question here is can I do that first as statement before the from or even after if it will work. 我很乐意在必要时共享更多代码,但是我在这里的主要问题是,我可以先作为声明在from之前还是之后执行该操作(如果它可以工作)。
Something like this might work: 这样的事情可能会起作用:
select distinct(users.user_id),
(select resi.curr_state
from ci_residents
AS resi_1 where resi_1.user_id = users.user_id) as current_state
FROM
ci_users AS users, ci_residents AS resi .....
WHERE stuff HAVING current_state = '".$php_variable_ill_use."'
There is a way to conditionally specify the output of a column, yes: you use a CASE
statement. 有一种方法可以有条件地指定列的输出,是的:使用
CASE
语句。 But it doesn't look like that's what you're doing. 但这似乎并不是您正在做的。 You seem to be specifying a relationship between the
resi
and users
tables, which you could normally accomplish using a JOIN, like this: 您似乎正在指定
resi
和users
表之间的关系,通常可以使用JOIN完成此关系,如下所示:
SELECT
DISTINCT(users.user_id),
resi.curr_state AS current_state
FROM ci_users AS users
JOIN ci_residents AS resi ON users.user_id = resi.user_id
Now, given the logic behind your request, I assume you want all user_ids, but only those states where a state exists. 现在,根据请求的逻辑,我假设您需要所有 user_id,但只需要存在状态的那些状态。 Is that correct?
那是对的吗? If so, use a
LEFT JOIN
to include all users
records, and include only resi
records when an associated record exists. 如果是这样,请使用
LEFT JOIN
包括所有users
记录,并在存在关联记录时仅包括resi
记录。
Please elaborate if you're trying to accomplish something other than what I've illustrated here. 如果您要完成我在此未说明的其他事情,请详细说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.