【问题标题】:mysql how to join these tables?mysql如何加入这些表?
【发布时间】:2012-12-05 07:42:25
【问题描述】:

我有几张表:型号、产品、规格、图片和商店。
它们的关联如下:

每个产品都属于(型号、商店)
每张图片都属于(产品)
每个规范都属于(产品)

我需要一份产品清单,

他们所属的商店(按 product.store_id)
其中 product.model_id=some_id
仅当产品有规格时(通过 spec.product_id) 仅当产品有图片时(按图片.product_id)

我需要什么类型的查询?

谢谢

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: mysql join


【解决方案1】:

你的定义很完整,可以直译过来:

select
  -- Selecting all fields of product and store. 
  -- You can refine this by only listing the fields you need.
  p.*,
  s.*
from
  -- need a list of products,
  product p
  -- with the store they belongs to (by product.store_id)
  inner join store s on s.store_id = p.store_id
where
  -- ONLY if there are specs for the product (by spec.product_id)
  exists
    (select
      'x'
    from
      spec ps 
    where
      ps.product_id = p.product_id) and
  -- ONLY if a product has pictures (by picture.product_id)
  exists
    (select
      'x'
    from
      pictures pp 
    where
      pp.product_id = p.product_id)

【讨论】:

  • 如果你检查我的查询,它将返回 OP 想要的行
【解决方案2】:

试试这个::

Select * from 
from 
product p
inner join model m on (p.model_id=m.id)
inner join store s on (p.store_id=s.id)
inner join picture pc on (p.picture_id=pc.id)
inner join spec sp on (p.spec_id=sp_id)

where product.model_id=some_id
GROUP BY product.id

【讨论】:

  • 常见错误。连接所有表将导致查询返回多行。例如,如果您有 3 张图片和 10 个规格,则为每个产品返回 30 行。
  • a select distinct p.*, s.* 可以解决这个问题...但它也可能使查询变慢
  • 添加后可以正常使用,但是查询不明显,不易扩展,违反规范,与其他数据库不兼容。我不会使用这个 MySQL 诡计。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
  • 2016-11-16
相关资源
最近更新 更多