1
$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 的 add date>last check date (from sql1) 并返回受影响的行数。

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

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

我不知道它应该是什么样子。提前谢谢

更新

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
4

2 回答 2

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 的正确语法,请适应您喜欢的驱动程序。

于 2012-06-04T15:54:31.887 回答
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 
于 2012-06-04T15:46:34.930 回答