【问题标题】:Mysql, how to avoid multiple joins on the same tableMysql,如何避免同一张表上的多个连接
【发布时间】:2014-05-08 03:19:30
【问题描述】:

有没有办法(使用一些 mysql 编程)来避免在同一个表上使用不同的别名进行多个连接?例如我有

SELECT *
FROM `container` AS `cont_link`  
LEFT JOIN `custom_field_string` AS `sf0` ON cont_link.id = sf0.container_id AND sf0.custom_field_id=60 
LEFT JOIN `custom_field_string` AS `sf3` ON cont_link.id = sf3.container_id AND sf3.custom_field_id=321 
LEFT JOIN `custom_field_string` AS `sf4` ON cont_link.id = sf4.container_id AND sf4.custom_field_id=322
LEFT JOIN `custom_field_int` AS `sf1` ON cont_link.id = sf1.container_id AND sf1.custom_field_id=319 
LEFT JOIN `custom_field_int` AS `sf2` ON cont_link.id = sf2.container_id AND sf2.custom_field_id=320  

Join with custom_field_string 表执行了 3 次,因为它具有不同的属性。我怎么能只用 1 个加入但保持不同的属性来做到这一点。 我遇到了达到 61 个连接限制的问题。

【问题讨论】:

  • 您需要重新考虑设计。我会说超过七个 JOIN 是不好的。你比那个高一个数量级。
  • 表中存在的数据示例以及您想要的输出在这里会很有帮助。
  • 这可以通过一组 MAX(CASE WHEN THEN END) 语句来完成 - 但它的执行速度不一定比你已经拥有的快。
  • @albanx:鉴于您所说的问题,每个JOIN 都很重要。我鼓励您分享您的整个查询,而不仅仅是您认为有问题的部分。
  • @albanx 我不是建议每个客户端配置一个平面表,而是一个用于所有 EAV 属性或每个实体类型一个。无论如何,另一种解决方案是为每组大约 60 个属性创建一个视图或临时表。然后,您可以将视图和/或表连接在一起。

标签: php mysql join


【解决方案1】:
SELECT *
FROM `container` AS `cont_link`  
LEFT JOIN `custom_field_string` AS `sf0` ON cont_link.id = sf0.container_id AND sf0.custom_field_id in (60, 321, 322);

如果只有三行匹配,您将在此处获得 3 个结果,而不是 1 行 3 列。

【讨论】:

    猜你喜欢
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    相关资源
    最近更新 更多