mysql - 一个神秘的 MySQL 选择查询

标签 mysql activerecord codeigniter-2 mysql-5.5

我有以下关系表,按关系描述为:

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。

再次突出显示内容:

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

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

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

最佳答案

WHERE 子句中排除 m2m.product=471 并检查符合该条件的产品:sl.product_type=8 和 listtype="short"

你写道“listtype="long"它神秘地带来了”一个记录。这并不神秘。您查找产品 471,并花费 listtype="long" 获得该产品,那么为什么您想要花费 listtype="short" 获得该产品呢?我假设这个 listtype

中不存在它

关于mysql - 一个神秘的 MySQL 选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24465989/

相关文章:

ruby-on-rails - 如何覆盖 gem 中 activerecord 中的验证调用?

codeigniter - Codeigniter 中函数 __construct() 内的变量

jQuery select(live,change) 和 .ajax 仅触发一次

mysql - Homestead - 连接到我的数据库

ruby-on-rails - 数据库/模型夹具和原始状态

php - 使用数组的 str_replace 是格式化一个人的姓氏的正确方法吗?

ruby-on-rails - 如何在 active_record 中禁用对模型中已更改属性的跟踪

php - fatal error : Class 'Model' not found in CodeIgniter

MySQL - 避免截断 float 据类型中的尾随零

php - 阻止谷歌索引成员(已将其个人资料设置为私有(private))个人资料