优化sql语句以减少MySQL服务器负载

时间:2012-06-04 15:36:28

标签: php mysql sql mysqli prepared-statement

$sql1 = "SELECT questions FROM last_check_date WHERE user_id=? ORDER BY questions DESC LIMIT 1";
$sql2 = "SELECT id FROM questions WHERE add_dt>?";

上面的陈述是做什么的?

当我执行sql1时,它会获得用户的最后检查日期。

然后我正在执行第二个查询,以获取所有ID,其中添加日期>最后检查日期(来自sql1)并返回受影响的行数。

我想要做的是将这2个语句合并为1,并优化查询计数。可能会出现以下问题:

$sql1中的用户没有行:必须选择sql2中的所有行并返回受影响的行数。

我无法弄清楚它应该是什么样子的...... Thx提前

更新

SHOW CREATE TABLE last_check_date;结果是

CREATE TABLE `last_check_date` (
  `id` int(11) unsigned NOT NULL,
  `user_id` bigint(20) unsigned NOT NULL,
  `questions` datetime DEFAULT NULL,
  `users` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

SHOW CREATE TABLE questions;

CREATE TABLE `questions` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `author_id` bigint(20) unsigned DEFAULT NULL,
  `question` text NOT NULL,
  `var_a` text NOT NULL,
  `var_b` text NOT NULL,
  `var_c` text NOT NULL,
  `var_d` text NOT NULL,
  `var_e` text NOT NULL,
  `subject` int(11) unsigned DEFAULT NULL,
  `chapter` int(11) unsigned DEFAULT NULL,
  `section` int(11) unsigned DEFAULT NULL,
  `paragraph` int(11) unsigned DEFAULT NULL,
  `rank` tinyint(2) NOT NULL,
  `add_dt` datetime NOT NULL,
  `answer` varchar(1) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_chapters-id` (`chapter`),
  KEY `fk_paragraphs-id` (`paragraph`),
  KEY `fk_subjects-id` (`subject`),
  KEY `fk_sections-id` (`section`),
  KEY `fk_author-id` (`author_id`),
  CONSTRAINT `fk_author-id` FOREIGN KEY (`author_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `fk_chapters-id` FOREIGN KEY (`chapter`) REFERENCES `chapters` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `fk_paragraphs-id` FOREIGN KEY (`paragraph`) REFERENCES `paragraphs` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `fk_sections-id` FOREIGN KEY (`section`) REFERENCES `sections` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `fk_subjects-id` FOREIGN KEY (`subject`) REFERENCES `subjects` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

2 个答案:

答案 0 :(得分:1)

见下文。我假设如果last_check_date中没有记录您仍然想要显示问题(在这种情况下所有记录都是这样)。

select q.id
from questions q
left outer join (
    select max(questions) as questions
    from last_check_date
    where user_id = ?
) lcd on q.add_date > lcd.questions
where user_id = ?
order by questions desc 

答案 1 :(得分:1)

$sql = "
    SELECT q.id 
    FROM questions q
    LEFT JOIN (
        SELECT questions 
        FROM last_check_date 
        WHERE user_id=? 
        ORDER BY questions 
        DESC LIMIT 1
    ) l ON q.add_dt > l.questions"

$rs = mysql_query($sql);
$rowcount = mysql_num_rows($rs);

我还不知道PDO / MYSQLI的正确语法,请适应您喜欢的驱动程序。