在SELECT语句中用另一个表替换另一个值

时间:2013-04-06 09:58:47

标签: mysql sql puppet

我正在尝试使用SQL语句在Puppet数据库中打印所有重复的[exported-resource]定义。

mysql> SELECT id,restype,host_id,source_file_id FROM resources    
    -> WHERE title IN (SELECT title FROM resources WHERE exported=1 
    -> GROUP BY title HAVING count(title) > 1) ORDER BY title;
+------+------------------------+---------+----------------+
| id   | restype                | host_id | source_file_id |
+------+------------------------+---------+----------------+
|  305 | Nagios::Client::Export |       2 |             18 |
|  333 | Nagios_host            |       2 |             39 |
|  605 | Nagios_hostextinfo     |       6 |              2 |
|  443 | Nagios_hostextinfo     |       2 |             39 |
|  499 | Nagios_host            |       6 |              2 |
|  770 | Nagios::Client::Export |       6 |             18 |
......
......

哪种工作正常,但如何从 hosts 表中检索/打印 hosts.name 而不是host_id。我只是无法重写上面的SQL语句。 hosts 表如下所示:

mysql> SELECT id,name  FROM hosts;
+----+-----------------------------------------+
| id | name                                    |
+----+-----------------------------------------+
|  2 | controller-dns-01.sdas.cloud.com        |
|  6 | controller-monitoring-01.sdas.cloud.com |
|  1 | controller-puppet.sdas.cloud.com        |
| 13 | talend-admin-01.sdas.cloud.com          |
| 15 | talend-jobserver-01.sdas.cloud.com      |
| 14 | talend-jobserver-02.sdas.cloud.com      |
+----+-----------------------------------------+

另外,有没有办法只打印主机名的第一部分(即只有controller-dns-01)而不是完整的字符串?任何人的任何建议都非常感谢。干杯!!

<小时/> 的更新
这是我的最终命令:以防万一其他人也在寻找找出Puppet导出资源重复定义的方法

mysql> CREATE INDEX index_resources_on_restypetitle ON resources (restype(12),title(12));
mysql> SELECT r.id, r.restype, r.title, SUBSTRING_INDEX(h.name,'.',1) AS 'host_name',
    -> SUBSTRING_INDEX(s.filename,'puppet/',-1) AS 'file_name', r.line FROM resources r 
    -> LEFT JOIN hosts h ON r.host_id = h.id LEFT JOIN source_files s ON r.source_file_id = s.id 
    -> WHERE MD5(CONCAT(restype,title,host_id)) 
    -> IN (SELECT MD5(CONCAT(restype,title,host_id)) FROM resources 
    -> WHERE exported=1 GROUP BY MD5(CONCAT(restype,title,host_id)) 
    -> HAVING COUNT(MD5(CONCAT(restype,title,host_id))) > 1) ORDER BY title;

SUBSTRING_INDEX(s.filename....)位可能需要根据配置重新调整。非常感谢thiella帮助我。

1 个答案:

答案 0 :(得分:3)

您需要使用您的resources表加入hosts表,使用SUBSTRING_INDEX显示点左侧字符串的一部分:

SELECT
  r.id, r.restype, r.host_id, r.source_file_id,
  SUBSTRING_INDEX(h.name, '.', 1)
FROM
  resources r LEFT JOIN hosts h
  ON r.host_id = h.id
WHERE
  r.title IN (SELECT title
            FROM resources
            WHERE export=1 
            GROUP BY title
            HAVING count(title) > 1)
ORDER BY
  r.title;