我有点困惑为什么这个简单的SQL查询不能使用搜索记录的别名。有两个不同的表名为'account'和'members'。我编写了一个子查询来计算成员表中的成员总数和来自帐户表的更多记录。所以,这里的查询不正常并且收到错误。
SELECT name, email, (SELECT Count(id) FROM members WHERE id = id) as totalMember, id
FROM account
WHERE
(name LIKE '%sa%' OR email LIKE '%sa%' OR totalMember LIKE '%sa%' OR
id LIKE '%sa%')
请建议我如何用别名写 LIKE ?
答案 0 :(得分:2)
您获得的错误可能与account
和members
表都有一个名为id
的列有关。要解决这个问题,请使用别名:
SELECT
a.name,
a.email,
(SELECT COUNT(m.id) FROM members m WHERE m.id = a.id) AS totalMember,
a.id
FROM account a
WHERE
(a.name LIKE '%sa%' OR a.email LIKE '%sa%' OR a.totalMember LIKE '%sa%' OR
a.id LIKE '%sa%');
编写查询的另一种方法是使用两个表之间的连接:
SELECT
a.name,
a.email,
COUNT(m.id) AS totalMember,
a.id
FROM account a
LEFT JOIN members m
ON a.id = m.id
WHERE
(a.name LIKE '%sa%' OR a.email LIKE '%sa%' OR a.totalMember LIKE '%sa%' OR
a.id LIKE '%sa%');
答案 1 :(得分:0)
你可以这样写:
SELECT name, email, (SELECT Count(id) FROM members b WHERE b.id = a.id) as
totalMember, id
FROM account a
WHERE a.name LIKE '%sa%' OR a.email LIKE '%sa%'OR a.id LIKE '%sa%'
答案 2 :(得分:0)
您不能在SELECT子句中创建的WHERE子句中使用别名,因为WHERE在SELECT子句之前执行。您需要使用嵌套查询。此外,您需要研究将totalMember作为整数进行比较的方式,并将其与字符串进行比较
SELECT *
FROM
(
SELECT name, email, (SELECT Count(id) FROM members WHERE id = a.id) as totalMember, id
FROM account a
) tab
WHERE
(name LIKE '%sa%' OR email LIKE '%sa%' OR totalMember LIKE '%sa%' OR
id LIKE '%sa%')