此查询在where子句中给出了一个错误未知列公司。我发现where子句首先运行,然后选择运行。这可能是错误。但我不知道如何纠正这个问题,以便在结果集中得到公司。
SELECT trnsdriverid,
name,
(SELECT transcompany.name
FROM transcompany,
transcompdriver
WHERE transcompany.trnscompid = transcompdriver.trnscompid) AS 'company',
address,
dob,
license,
telephone
FROM transcompdriver
WHERE ? LIKE 'All'
OR name LIKE '%"+keyword+"%'
OR company LIKE '%"+keyword+"%'
OR trnsdriverid LIKE '%"+keyword+"%'
答案 0 :(得分:1)
您无法在where语句中引用列别名。您应该重写此查询以使用JOIN,然后对实际的TransCompany.name列进行过滤,例如:
select
d.trnsDriverID
,d.name
,c.name as [Company]
,d.address
,d.dob
,d.license
,d.telephone
from
TransCompDriver d
join
TransCompany c
on
c.trnscompid = d.trnscompid
where
? = 'All'
or
d.name like '%" + keyword + "%'
or
c.name like '%" + keyword + "%'
or
d.trnsDriverID like '%" + keyword + "%'
此外,不要使用简单等于运算符的LIKE
。我将上面的查询更改为使用= 'All'
。
答案 1 :(得分:0)
你应该使用连接而不是子选择来做这件事。我会推荐这个:
SELECT
d.trnsDriverID,
d.name,
c.name AS `company`,
d.address,
d.dob,
d.license,
d.telephone
FROM
TransCompDriver AS d
INNER JOIN TransCompany AS c
ON d.trnsCompID = c.trnsCompID
WHERE
? like 'All'
OR d.name LIKE '%"+keyword+"%'
OR `company` LIKE '%"+keyword+"%'
OR d.trnsDriverID LIKE '%"+keyword+"%'
答案 2 :(得分:0)
拉取“公司”列的子查询没有匹配的行数,请尝试使用join语句
select trnsDriverID, name, t1.name AS company, address, dob, license, telephone
from TransCompDriver JOIN (select trnsDriverID, name,
(select TransCompany.name from TransCompany LEFT JOIN TransCompDriver
ON TransCompany.trnsCompID=TransCompDriver.trnsCompID) AS t1
where ? like 'All' or name like '%"+keyword+"%' or company like '%"+keyword+"%'
or trnsDriverID like '%"+keyword+"%'