在查询子句中使用LIKE %%,其中包含来自不同表的多个值

时间:2014-01-06 09:20:17

标签: mysql sql

我有一个从三个表中获取值的基本查询。三个表:company,classes_by_company和person。我在名为company_id的所有表中都有一个外键。在where子句中,我使用LIKE与随机值进行比较,获取可能具有匹配项的任何结果的值。但我没有成功。我在sql行WHERE a.id LIKE %1% OR a.company_id LIKE %3% OR c.count LIKE %1% OR p.count LIKE %1%中收到错误。如何将从这三个表中获取的所有值与随机值进行比较以查看是否存在匹配? SQLFIDDLE

SELECT a.id, a.company_id, a.status,
       c.count AS classes_per_company,
       p.count AS employees_per_company
FROM company a
LEFT JOIN (SELECT company_id, COUNT(*) as count
           FROM classes_by_company
           GROUP BY company_id) c
       ON a.company_id = c.company_id
LEFT JOIN (SELECT company_id, COUNT(*) as count
           FROM person
           GROUP BY company_id) p
       ON a.company_id = p.company_id
WHERE a.id LIKE %1% OR a.company_id LIKE %3% OR c.count LIKE %1% OR p.count LIKE %1% 

表架构:

CREATE TABLE company
    (
     id int auto_increment primary key,
     company_id int,
     status varchar(20)
    );

CREATE TABLE classes_by_company
(
 id int auto_increment primary key,
 company_id int,
 class_name varchar(20)
);

CREATE TABLE person
(
 id int auto_increment primary key,
employee_id int,
 company_id int,
 person_name varchar(20)
);

2 个答案:

答案 0 :(得分:3)

LIKE后面必须跟一个字符串,所以它应该是:

WHERE a.id LIKE '%1%'
   OR a.company_id LIKE '%3%'
   OR c.count LIKE '%1%'
   OR p.count LIKE '%1%'

答案 1 :(得分:0)

id是一个整数列; LIKE运算符依赖于文本数据类型,例如nvarchar的。

您可以将ID转换为字符串,例如在什么地方(a.id AS VARCHAR(10))喜欢'%1%'...

请注意%1%左右的单引号。