0

我的 SQL 语句看起来像这样

SELECT SQL_CALC_FOUND_ROWS q.id, q.question, sb.subject, c.chapter, sc.section, p.paragraph 
FROM questions AS q
     , subjects AS sb
     , sections AS sc
     , chapters AS c
     , paragraphs AS p 
WHERE (sb.id=q.subject AND c.id=q.chapter AND sc.id=q.section AND p.id=q.paragraph) AND (q.author_id=1) 
ORDER BY  q.id asc 
LIMIT 0, 25

如您所见,这些表通过 id 相互关联。问题是,我得到subject的是表格列questions而不是表格subjectsubjects。我在这里想念什么?

笔记

我提供了主题作为示例。实际上所有三个部分 AS sc、章节 AS c、段落 AS p 都不起作用。我得到的只是主题。

4

2 回答 2

2

显然,您的问题中的查询很好,但仍要使用此语句来挖掘它,并查看 subject_subject 列中出现的内容

SELECT SQL_CALC_FOUND_ROWS q.id, q.question, sb.subject as subjects_subject, c.chapter, sc.section, p.paragraph 
FROM questions AS q
     , subjects AS sb
     , sections AS sc
     , chapters AS c
     , paragraphs AS p 
WHERE (sb.id=q.subject AND c.id=q.chapter AND sc.id=q.section AND p.id=q.paragraph) AND (q.author_id=1) 
ORDER BY  q.id asc 
LIMIT 0, 25

希望这可以帮助。

于 2012-05-13T17:18:50.837 回答
1

我通常明确地使用 JOIN 语法。这有时会给你更好的错误输出,以帮助追踪问题。

这是原始格式,因此您可以轻松查看差异。

SELECT SQL_CALC_FOUND_ROWS q.id, q.question, sb.subject, c.chapter, sc.section, p.paragraph 
FROM questions AS q, 
     subjects AS sb, 
     sections AS sc, 
     chapters AS c, 
     paragraphs AS p 
WHERE (sb.id=q.subject 
       AND c.id=q.chapter 
       AND sc.id=q.section 
       AND p.id=q.paragraph) 
      AND (q.author_id=1) 
ORDER BY  q.id asc 
LIMIT 0, 25

这是经过编辑的版本 - 请注意定义表如何挂钩的 WHERE 子句参数已作为 ON 子句向上移动到表名列表中。这是 INNER JOIN 语法的一部分,即: INNER JOIN ON 。

SELECT SQL_CALC_FOUND_ROWS q.id, q.question, sb.subject, c.chapter, sc.section, p.paragraph 
FROM questions AS q
  INNER JOIN subjects AS sb ON sb.id = q.subject
  INNER JOIN sections AS sc ON sc.id = q.section 
  INNER JOIN chapters AS c ON c.id = q.chapter
  INNER JOIN paragraphs AS p ON p.id = q.paragraph
WHERE (q.author_id=1) 
ORDER BY  q.id asc 
LIMIT 0, 25

如果您尝试直接针对 MySQL 运行它,会发生什么?

于 2012-05-13T17:27:16.687 回答