【问题标题】:join 3 mysql tables with condition加入有条件的 3 个 mysql 表
【发布时间】:2014-03-14 13:44:57
【问题描述】:

我有 3 张桌子

product
-product_id
-name
-image

product_description
-product_id
-product_description
-product_attributes

product_store
-product_id
-store_id

我需要做的是从productproduct_description 表中获取产品名称、描述和图像,并且产品应该只来自product_store 表中的store_id = 0 or 1

product_store 表只有 product_idstore_id 字段

到目前为止,我已经加入了 product 和 product_description 表。但我仍在尝试加入product_store 表以检查产品是否来自正确的商店。

SELECT p.product_id, pd.name,p.image FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) order by p.product_id DESC LIMIT 3

谁能告诉我如何加入第三张表并检查它是否来自正确的 store_id?

【问题讨论】:

  • 请给我清楚的字段名称,无法理解您的详细信息..
  • @jmail 我更新了帖子..
  • 根据您上面的表格描述,表格product_description 没有name 列。您可能希望将您的声明更改为p.name

标签: mysql sql join


【解决方案1】:

在聚会中添加第三张桌子(我的意思是加入),像这样:

SELECT p.product_id, pd.name,p.image 
FROM product p 
LEFT JOIN product_description pd 
ON (p.product_id = pd.product_id)
JOIN product_store ps
ON (p.product_id = ps.product_id AND ps.store_id IN (0,1))
ORDER BY p.product_id DESC 
LIMIT 3

【讨论】:

    【解决方案2】:
    select distinct p.product_id, d.name, p.image
    from product p join product_description d on
      p.product_id = d.product_id join product_store s on
      p.product_id = s.product_id
    where
      s.store_id in (0, 1)
    order by p.product_id DESC LIMIT 3
    

    DISTINCT 是必需的,因为您可能会与 product_store 连接两次,并重复行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多