mysql - 在包含两个表的记录的交叉表的单个查询中选择三个记录 - MYSQL

标签 mysql join

我有一个名为“product”的主表,它与三个表链接:

"product_type", 
"feature", 
"type_feature" 

和一个名为“product_feature”的交叉表,其中包含同一产品的多个功能。

一条记录示例:

我有类似的东西:

产品类型

id_product_type    name
    1              Phone

功能

id_feature   name
    1         Memory 
    2         Color 
    3         Memory Ram

功能类型

id_feature_type  id_feature  value
      1              1         16GB
      2              1         32GB
      3              2         Blue
      4              2         Black
      5              3         2GB
      6              3         3GB  

产品

id_product id_product_type  price quantity  model
    1           1           100$    5      Moto-G7 

交叉表“product_feature”(链接到“product”、“feature”和“feature_type”):

id_feature id_product id_feature_type
    1          1            1
    2          1            3
    3          1            6

我想要查询显示这个:

id_product   type_name price quantity   model    feature_name  value  
    1        Phone     100$     5      Moto-G7     Memory       16GB
feature_name2 value2  feature_name3   value3
    Color      Blue    Memory Ram       3GB

我尝试了这一点,但只有一个 feature_name 和 value,而我需要三个:

  SELECT p.id_product, pt.name, model, price, quantity, f.name AS feature, ft.value
  FROM product p
  LEFT JOIN product_type pt ON pt.id_product_type = p.id_product_type 
  LEFT JOIN product_feature pf ON pf.id_product = p.id_product
  LEFT JOIN feature f ON f.id_feature = pf.id_feature
  LEFT JOIN feature_type ft ON ft.id_feature_type = pf.id_feature_type
  GROUP BY p.id_product;

最佳答案

尝试这个查询,它会给你结果:

SELECT product.*, product_type.name as TypeName, (SELECT CONCAT( GROUP_CONCAT(feature_type.value), "|", GROUP_CONCAT(feature.name) ) FROM `product_feature` INNER JOIN feature_type on product_feature.id_feature_type = feature_type.id_feature_type INNER JOIN feature on feature_type.id_feature = feature.id_feature WHERE product_feature.id_product=1 GROUP BY product_feature.id_product) as options FROM `product` LEFT JOIN product_type on product.id_product_type = product_type.id_product_type

enter image description here

您将获得产品的选项,并且必须通过“|”来爆炸()这些选项您可以使用 $count= count(explode("|", $options)) 来计算有多少个选项

通过这种方式你可以获得所有选项。

关于mysql - 在包含两个表的记录的交叉表的单个查询中选择三个记录 - MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55024150/

相关文章:

javascript - 带有超时的JS函数应该每4秒发送一次数据,但只发送1次

Ubuntu 上的 Mysql : ERROR 1045 (28000)

mysql - Rails 中每个循环的帮助。尝试统计每个表中的数据。

mysql - 非常小的 MySQL 表会忽略索引吗?

mysql - 创建 SQL 表,如何将 BIT 条目转换为文本 YES 或 NO?

mysql - 在 Vapor 中将多个连接与过滤器结合起来

sql - 使用 SQL 查询的 TreeView

php - MySQL 全外连接

SQL 连接问题 : Third table's fields not displaying in Excel but in SQL

mysql - 在 MySQL 中使用 join 代替该子查询