Ta [2.] vypada konkretne nejak takhle
CREATE TABLE IF NOT EXISTS `nz_forms` (
`id_form` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_root` int(10) unsigned DEFAULT NULL,
`status` int(10) unsigned DEFAULT NULL,
`name0` varchar(40) DEFAULT NULL,
`name1` varchar(40) DEFAULT NULL,
`name2` varchar(40) DEFAULT NULL,
`name3` varchar(40) DEFAULT NULL,
`time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id_form`),
KEY `id_group` (`status`),
KEY `id_root` (`id_root`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=10 ;
--
-- Dumping data for table `nz_forms`
--
INSERT INTO `nz_forms` (`id_form`, `id_root`, `status`, `name0`, `name1`, `name2`, `name3`, `time`) VALUES
(1, 1, 1, 'aaa 0xyyy', 'bbb 0xx', 'ccc 0xs', 'ddd 0xa', '2016-11-25 09:20:59'),
(3, 1, 0, 'ddd', 'ddd', 'ddd', 'ddd', '2016-11-25 12:26:54'),
(4, 1, 1, 'ddd', 'ddd', 'ddd', 'ddd 0xa', '2016-11-25 09:29:59'),
(5, NULL, 2, 'fsd', 'fds', 'xxxxxxa', 'xxxxxxa', '2016-11-25 09:21:59');
$pref = '`b`.';
$query_inner = "
SELECT
IF(c.`id_root` IS NOT NULL, c.`id_root`,c.`id_form`) AS `id_root`,
Max(c.`time`) AS `time`
FROM `$tbl` c
GROUP BY c.`id_root`
";
$query1 = "SELECT COUNT(*) AS 'count' FROM ($query_inner) AS ".$pref.$where2;
// $query2 = "SELECT $query_keys FROM `$tbl`".$where2;
$query2 = "
SELECT $query_keys
FROM ($query_inner) AS `a`
LEFT JOIN `$tbl` `b` ON (`b`.`id_root`=`a`.`id_root` OR `b`.`id_form`=`a`.`id_root`) AND `b`.`time`=`a`.`time`
".$where2;
$query2 .= " ORDER BY ".$pref.$SQL->escapeKey($table_order)." LIMIT $table_start, $table_count";