MySQL WhereIN子查询限制

时间:2014-04-16 20:20:09

标签: mysql subquery where-in

我们说我有这个大规模的查询:

SELECT
    entity_documents.id,
    entity_fields.name,
    entity_document_fields.value,
    entity_documents.created_at,
    entity_documents.updated_at

FROM entity_documents

LEFT JOIN entity_document_fields
    ON entity_documents.id = entity_document_fields.entity_document_id

LEFT JOIN entity_fields
    ON entity_document_fields.entity_field_id = entity_fields.id

WHERE entity_documents.id IN (
    SELECT
        entity_document_fields.entity_document_id

    FROM entities

    LEFT JOIN entity_fields
        ON entities.id = entity_fields.entity_id

    LEFT JOIN entity_document_fields
        ON entity_fields.id = entity_document_fields.entity_field_id

    WHERE entities.name = "Pages"
    AND entity_fields.name = "Slug"
    AND entity_document_fields.value = '/'

    LIMIT 10
);

当我运行它时,MySQL会出现以下错误:

This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

有没有解决这个问题的方法?

我正在使用MySQL 5.5.34。我是否需要升级或是否有更好的解决方案来限制我的子查询?

提前致谢

1 个答案:

答案 0 :(得分:1)

将条件移至from子句:

SELECT
    entity_documents.id,
    entity_fields.name,
    entity_document_fields.value,
    entity_documents.created_at,
    entity_documents.updated_at

FROM entity_documents LEFT JOIN
     entity_document_fields
     ON entity_documents.id = entity_document_fields.entity_document_id LEFT JOIN 
     entity_fields
     ON entity_document_fields.entity_field_id = entity_fields.id JOIN
     (SELECT DISTINCT entity_document_fields.entity_document_id
      FROM entities LEFT JOIN
           entity_fields
           ON entities.id = entity_fields.entity_id LEFT JOIN
           entity_document_fields
           ON entity_fields.id = entity_document_fields.entity_field_id
      WHERE entities.name = 'Pages' AND
            entity_fields.name = 'Slug' AND
            entity_document_fields.value = '/'
      LIMIT 10
     ) filter
     on filter.entity_document_id =  entity_documents.id;

如果您知道子查询返回的值已经是唯一的,则不需要distinct