具有多个连接的复杂连接查询

时间:2013-01-23 04:18:29

标签: php mysql sql yii

我有以下表格

产品

id                      int(11)         AUTO_INCREMENT                                                  
name                    varchar(254)                                                                     
product_category_id     int(11)

产品属于 ProductCategories 中的 a 类别。一个类别有子类别(自我加入)

id                      int(11)         AUTO_INCREMENT                                                  
name                    varchar(254)                                                                     
parent_id               int(11)

产品还有 图标存储在 ProductMedia 中。

id                      int(11)         AUTO_INCREMENT                                                  
url                     varchar(254)                                                  
type                    enum('icon','banner','video')                                                                     
product_id              int(11)

最有效的方法是使所有产品都具有属于某个类别的关联图标,包括其子类别中的产品(如果有)。

示例:

Product  
1. iphone              - Mobile(category)
2. sIII                - Mobile (category) 
3. liginting connector - Cable(category)
4. iPhone USB charger  - Charger(category)

ProductCategories
1. Mobile   - 0(parent)
2. Cables   - 1(parent)
3. Sim      - 1
4. Shoes    - 0
5. Chargers - 2   

当我搜索移动类别时,它需要向我提供所有4种产品,根据电缆需要提供最后2个但在充电器下只有最后一个

2 个答案:

答案 0 :(得分:1)

使用联接

SELECT 
    p.*,
    pc.name,
    pm.url,
    pm.type
FROM Product as p
LEFT JOIN ProductMedia as pm ON pm.product_id = p.id
LEFT JOIN ProductCategories as pc ON pc.id = p.product_category_id

你可以这样做 编辑:

select
  p.name,
  ifnull(pc.Category,pc.name) as Category,
  pm.type
from product as p
  left join (select
           l.id        as id,
           l.name,
           l.parent_id,
           if(r.parent_id <> 0,l.name, CONCAT(l.name,'|',r.name )) as Category
         from productcategories as l
           left join productcategories as r
         on r.id = l.parent_id) as pc
    on pc.id = p.id
  left join productmedia as pm
    on pm.product_id = p.id

输出

name                        |   Category            |   type 
----------------------------------------------------------------
iphone                      |   Mobile              |   banner 
sIII                        |   Charger|Mobile      |   icon 
iphone liginting connector  |   HeadPhones|Mobile   |   video 

您可以使用php explode爆炸类别

答案 1 :(得分:0)

根据我从你那里得到的问题,你想要这样的东西。

SELECT 
    p.*,
    m.url,
    m.type
FROM Product as p
LEFT JOIN ProductMedia as m ON m.product_id = p.id
LEFT JOIN ProductCategories as c ON c.id = p.product_category_id
where c.id='Mobile'