【问题标题】:mysql:best way to optimize this sql querymysql:优化此 sql 查询的最佳方法
【发布时间】:2014-07-19 18:43:49
【问题描述】:

我想获得从此查询中获取结果的最佳方法

这是我的表格说明

学校

CREATE TABLE `schools` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `user` mediumint(5) NOT NULL,
 `gender` tinyint(1) NOT NULL,
 `time` int(11) NOT NULL,
 `status` tinyint(2) NOT NULL,
 `number` mediumint(6) NOT NULL,
 `name` varchar(75) NOT NULL,
 `address` varchar(75) NOT NULL,
 `admin` varchar(50) NOT NULL,
 `admin_phone` varchar(20) NOT NULL,
 `admin_email` varchar(30) NOT NULL,
 `school_phone` varchar(20) NOT NULL,
 `learn` tinyint(2) NOT NULL,
 `mr7la` tinyint(2) NOT NULL,
 `sfof` smallint(3) NOT NULL,
 `fswl` smallint(3) NOT NULL,
 `json` text NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `user` (`user`),
 KEY `status` (`status`),
 KEY `learn` (`learn`),
 KEY `mr7la` (`mr7la`),
 KEY `number` (`number`)
) ENGINE=MyISAM AUTO_INCREMENT=20 DEFAULT CHARSET=utf8

3agz

CREATE TABLE `3agz` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT,
 `school` int(11) NOT NULL,
 `tkss` int(11) NOT NULL,
 `teacher_7ess` int(11) NOT NULL,
 `teacher_master_7ess` int(11) NOT NULL,
 `time_added` int(11) NOT NULL,
 `reported` int(11) NOT NULL DEFAULT '0',
 `fixed` int(11) NOT NULL,
 `info` text NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `school` (`school`,`tkss`,`teacher_7ess`,`fixed`),
 KEY `school_2` (`school`),
 KEY `tkss` (`tkss`),
 KEY `reported` (`reported`),
 KEY `time_added` (`time_added`),
 KEY `school_3` (`school`,`time_added`),
 KEY `school_4` (`school`,`fixed`)
) ENGINE=InnoDB AUTO_INCREMENT=85 DEFAULT CHARSET=utf8

这是用于此的 SQL Fiddle

http://sqlfiddle.com/#!2/3313e0/4


你可以看到我使用的她的我的 sql 查询

SELECT
    schools.* , ( select count(id) from 3agz where 3agz.school = schools.id and fixed = 0 ) as has_3agz
           FROM
                schools
           WHERE
                ( select count(id) from 3agz where 3agz.school = schools.id and fixed = 0 ) > 0

limit 10

解释是

学校 => 小学:所有

3agz => 相关子查询:参考

3agz => 相关子查询:参考

请问我可以这样做吗?最好的方法是什么

1 - 我可以忽略第二个子查询在哪里并得到它取决于选择中的第一个子查询

2- 如果第一个答案是你不能 我可以忽略第一个子查询 [ has_3agz 别名] 执行此查询后,我循环显示结果 [schools ids]

然后像这样进行第二次查询

例如,第一个查询返回学校 ID 1 , 2 , 3 , 4

select school , count(id) from 3agz where school in ( 1 , 2 , 3 , 4 ) and fixed = 0

将每个计数附加到数组中的学校

希望你能理解我

最好的问候

【问题讨论】:

    标签: php mysql optimization query-optimization


    【解决方案1】:
    SELECT schools.*, count(*) as has_3agz from schools
    LEFT JOIN 3agz on 3agz.school = schools.id and fixed = 0
    GROUP BY schools.id;
    

    【讨论】:

    • 考虑做 OP 想要做的事情(即忽略计数为 0 的项目),如果您需要 LEFT JOIN,则需要 HAVING has_3agz > 0,或者可能只是将 LEFT JOIN 更改为 INNER JOIN .
    • 感谢@Kickstart 的评论,我已经使用了,因为经理可以查询 has_3agz > 0 :)
    • 啊,是的,对不起,我错过了关于跳过那些 0 的部分。正确的做法是如果你想跳过 0 将其更改为内部连接,或者如果你想使用 have想要计数的另一个条件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 2014-04-15
    相关资源
    最近更新 更多