我正在尝试查询MySQL中的数据库。我需要将它与传统表中的另一个查询联合起来,所以我想在php中完成所有这些操作。以下是我目前正在做的事情,我认为这可能效率很低。
这是数据库的示例:http://sqlfiddle.com/#!2/874e19/3
这就是我选择信息的方式:
$device = $mysqli->query("SELECT
DISTINCT
serial
FROM
device
ORDER BY
edit_date
DESC
")or die(mysql_error());
while ($row = $device->fetch_assoc()) {
$serial = $row['serial'];
$device_data = $mysqli->query('SELECT
(SELECT data_value FROM device WHERE (data_type = \'device_name\' AND serial = \''. $serial . '\')) as hostname,
(SELECT data_value FROM device WHERE (data_type = \'unit\' AND serial = \''. $serial . '\')) as unit,
(SELECT data_value FROM device WHERE (data_type = \'version\' AND serial = \''. $serial . '\')) as version,
(SELECT data_value FROM device WHERE (data_type = \'lan_ip\' AND serial = \'' . $serial .'\')) as location_ip,
(SELECT data_value FROM device WHERE (data_type = \'wan_ip\' AND serial = \'' . $serial .'\')) as wan_ip,
(SELECT data_value FROM device WHERE (data_type = \'status\' AND serial = \'' . $serial .'\')) as status
')or die(mysql_error());
}
有更好的方法吗?
答案 0 :(得分:1)
我会在一个查询中执行此操作,以获得最佳性能和简单性。像这两个解决方案应该有效:
SELECT DISTINCT d.serial, d.data_value AS hostname, d1.data_value AS unit, d2.data_value AS version, d3.data_value AS lan_ip, d4.data_value AS wan_ip, d5.data_value AS status
FROM device d
LEFT JOIN device d1 ON d.serial = d1.serial AND d1.data_type = 'unit'
LEFT JOIN device d2 ON d.serial = d2.serial AND d2.data_type = 'version'
LEFT JOIN device d3 ON d.serial = d3.serial AND d3.data_type = 'lan_ip'
LEFT JOIN device d4 ON d.serial = d4.serial AND d4.data_type = 'wan_ip'
LEFT JOIN device d5 ON d.serial = d5.serial AND d5.data_type = 'status'
WHERE d.data_type = 'device_name'
ORDER BY d.edit_date DESC;
或
SELECT DISTINCT d.serial, d.data_value AS hostname,
(SELECT data_value FROM device WHERE (data_type = 'unit' AND serial = d.serial)) AS unit,
(SELECT data_value FROM device WHERE (data_type = 'version' AND serial = d.serial)) AS version,
(SELECT data_value FROM device WHERE (data_type = 'lan_ip' AND serial = d.serial)) AS location_ip,
(SELECT data_value FROM device WHERE (data_type = 'wan_ip' AND serial = d.serial)) AS wan_ip,
(SELECT data_value FROM device WHERE (data_type = 'status' AND serial = d.serial)) AS status)
FROM device d
WHERE d.data_type = 'device_name'
ORDER BY d.edit_date DESC;