JOIN返回太多结果

时间:2012-08-11 08:09:50

标签: mysql query-optimization

这个问题与:

有关

Another unknown column name error in ON clause

我的实际查询:

    SELECT  c.title AS title
      , c.introtext AS body
      , c.state AS state
      , c.created AS created
      , c.created_by AS uid
      , c.modified AS modified
      , c.modified_by AS modified_uid
      , c.published AS published
      , c.published_by AS published_uid
      , jc.title AS category
    FROM  jos_content AS c
    INNER JOIN jos_categories AS jc 
    ON c.sectionid = jc.section 
    WHERE c.sectionid = 4

我希望按部分和内容的类别名称获取内容。

我知道在jos_content表中,id为4的部分的行是8000,但是这个查询会给我带来177k行。

我尝试将INNER JOIN更改为LEFT等并使用DISTINCT,但它无济于事

表格列:

jos_content:    

id, title, introtext, state, created, created_by etc


jos_categories:

  id, section (id of sections, names doesn't naming convention IMO, its Joomla 1.5 db BTW), title

jos_sections:
  id, title

我想得到的是:

jos_content.title(etc)与所选部分的jos_categories_name

2 个答案:

答案 0 :(得分:1)

由于缺乏信息,我无法告诉您如何编写查询,但我可以告诉您为什么您在现有查询中得到了错误的结果。

如果这是表格的内容(简化);

jos_content:    id      sectionid      title
                 1              4      Content 1 
                 2              4      Content 2

jos_categories  id        section      title
                 1              4      Category 1
                 2              4      Category 2

...然后运行查询(简化)......

SELECT  c.title AS title
     , jc.title AS category
FROM  jos_content AS c
INNER JOIN jos_categories AS jc 
ON c.sectionid = jc.section 
WHERE c.sectionid = 4

...因此,您将获得4行(第4节中内容项数量的第4部分中的类别数量)。

title        category
Content 1    Category 1
Content 2    Category 1
Content 1    Category 2
Content 2    Category 2

原因是您在查询中没有任何内容将内容绑定到类别,您通过部分查询,它为您提供了许多可能的查询答案。

答案 1 :(得分:0)

或者,尝试这个脚本。[SectionId]设置中的[Content]表分组:

SELECT  c.title AS title
      , c.introtext AS body
      , c.state AS state
      , c.created AS created
      , c.created_by AS uid
      , c.modified AS modified
      , c.modified_by AS modified_uid
      , c.published AS published
      , c.published_by AS published_uid
      , jc.title AS category
    FROM  jos_content AS c
    INNER JOIN jos_categories AS jc 
    ON c.sectionid = jc.section and c.sectionid=4
    gorup by c.sectionid