0

此查询在 where 子句中给出错误 unknown column company。我发现 where 子句首先运行,然后 select 运行。这可能是这里的错误。但我不知道如何纠正这一点,以便让公司进入结果集。

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+"%' 
4

3 回答 3

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'.

于 2013-03-25T17:07:36.270 回答
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+"%'
于 2013-03-25T17:07:55.833 回答
0

提取列“公司”的子查询没有匹配的行数,请尝试使用连接语句

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+"%'
于 2013-03-25T17:10:02.997 回答