2表连接WHERE子句

时间:2017-08-23 07:27:39

标签: mysql ocs

我正在使用Mysql,我很难尝试从SELECT查询中获取结果。我有两张桌子。第一个表硬件,第二个表softwares_name_cache:

desc hardware;
+----------------+---------------------+------+-----+---------+----------------+
| Field          | Type                | Null | Key | Default | Extra          |
+----------------+---------------------+------+-----+---------+----------------+
| ID             | int(11)             | NO   | PRI | NULL    | auto_increment |
| DEVICEID       | varchar(255)        | NO   | PRI | NULL    |                |
| NAME           | varchar(255)        | YES  | MUL | NULL    |                |
| WORKGROUP      | varchar(255)        | YES  | MUL | NULL    |                |
| USERDOMAIN     | varchar(255)        | YES  |     | NULL    |                |
| OSNAME         | varchar(255)        | YES  | MUL | NULL    |                |
| OSVERSION      | varchar(255)        | YES  |     | NULL    |                |
| OSCOMMENTS     | varchar(255)        | YES  |     | NULL    |                |
| PROCESSORT     | varchar(255)        | YES  |     | NULL    |                |
| PROCESSORS     | int(11)             | YES  |     | 0       |                |
| PROCESSORN     | smallint(6)         | YES  |     | NULL    |                |
| MEMORY         | int(11)             | YES  | MUL | NULL    |                |
| SWAP           | int(11)             | YES  |     | NULL    |                |
+----------------+---------------------+------+-----+---------+----------------+

desc softwares_name_cache;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| ID    | int(11)      | NO   | PRI | NULL    | auto_increment |
| NAME  | varchar(255) | YES  | UNI | NULL    |                |
+-------+--------------+------+-----+---------+----------------+

我正在尝试为每个SQL服务器获取处理器(sum(hardware.PROCESSORN)的数量,因此我需要从表软件加入(OSNAME LIKE '%Server%')条件,并从表software.sncache_cache中加入(softwares_name_cache where name like '%Microsoft SQL Server 20%')条件。

2 个答案:

答案 0 :(得分:0)

由于字段"名称"对于hardware和softwares_name_cache表都很常见。在你的where条件给你过滤名字提交。因此它会抛出错误。试试这样:

SELECT sum(hardware.PROCESSORN) 
FROM hardware 
inner join softwares_name_cache on hardware.id = softwares_name_cache.ID 
WHERE (OSNAME LIKE '%Server%') AND softwares_name_cache.NAME IN  IN (select NAME from 
      softwares_name_cache where name like '%Microsoft SQL Server 20%');

答案 1 :(得分:0)

SELECT sum(hardware.PROCESSORN) 
FROM hardware 
inner join softwares_name_cache on hardware.ID= softwares_name_cache.ID 
WHERE (OSNAME LIKE '%Server%') 
AND softwares_name_cache.NAME IN 
    (
     select softwares_name_cache.NAME
     from softwares_name_cache 
     where softwares_name_cache.NAME like '%Microsoft SQL Server 20%'
    );