【问题标题】:A mysterious MySQL select query一个神秘的 MySQL 选择查询
【发布时间】:2014-06-28 10:41:19
【问题描述】:

我有以下按关系描述的关系表:

Table product(id(PK),name,type(FK),category(FK),brand(FK));

Table Specification (id(PK),name);

Table product_specification_m2m (id(PK),specification(FK),value);

Table speclist (id(PK),specification(FK),product_type(FK),listtype);

对产品运行此查询会带来预期的结果:

select m2m.specification,sl.product_type,sl.listtype 
from product_specification_m2m m2m 
     left join specification s on  
     s.id = m2m.specification
     left join speclist sl on 
     sl.specification = m2m.specification
     where m2m.product=626 and sl.product_type=8 and listtype="short";

     +---------------+--------------+----------+
     | specification | product_type | listtype |
     +---------------+--------------+----------+
     |            98 |            8 | short    |
     |           100 |            8 | short    |
     +---------------+--------------+----------+
     2 rows in set (0.00 sec)

但对于运行此查询的 product_type=8 的任何其他产品 一个空数组! :

select m2m.specification,sl.product_type,sl.listtype 
from product_specification_m2m m2m 
     left join specification s on  
     s.id = m2m.specification
     left join speclist sl on 
     sl.specification = m2m.specification
     where m2m.product=471 and sl.product_type=8 and listtype="short";

     0 rows in set (0.00 sec)

     For listtype="long" it mysteriously brings :
     +---------------+--------------+----------+
     | specification | product_type | listtype |
     +---------------+--------------+----------+
     |           135 |            8 | long     |
     +---------------+--------------+----------+
     1 rows in set (0.00 sec)

谁能指出我的谜团(或者我太笨了,花了 3 个小时后我也找不到它!)在这里继续!

编辑:

speclist 表采用一些规范并将它们分类为“短”列表和“长”列表。这就是我在网页上展示它们的方式。候选名单保留 2/3 规格 ID,而长名单通常保留 9/10 规格 ID。

再次强调:

每种产品类型都有一组规格。

每个产品都有该类型的规范子集(产品和规范所属的)

每个产品又有两个规格子集,在规格表中按“短”和“长”分类。

【问题讨论】:

  • 请提供列类型并检查长字段中的任何空格。测试尝试列表类型,如“%short%”

标签: mysql activerecord codeigniter-2 mysql-5.5


【解决方案1】:

WHERE 子句中排除 m2m.product=471 并检查在该条件下存在哪些产品:sl.product_type=8 和 listtype="short"

您为“listtype="long" 它神秘地带来”了一条记录。没有奥秘。您寻找产品 471 并通过 listtype="long" 获得它,那么为什么要为 listtype="short" 获得该产品?我假设它不存在这个 listtype

【讨论】:

  • @edam 请在没有“m2m.product=471”条件的情况下发布查询输出。
  • 它只是带来了属于 sl.product_type=X 的整套规范;
  • @edam 是的,当然。现在检查您是否在该集合中有 product=471。
猜你喜欢
  • 2010-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-13
  • 2016-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多