如何连接这些表以获得正确的结果

时间:2012-02-24 23:33:45

标签: mysql

我一直试图弄清楚这个查询几个小时但没有成功。

我有3张桌子:   - jstyle_category   - 风格   - subsite_style_alias

表格有这个模式:

  • jstyle_category:
    • style_id
    • CATEGORY_ID
    • subsite_id(INT)
    • SORT_ORDER
    • 有效(ENUM:y,n)
  • 风格
    • ID
    • subsite_id(STRING,逗号分隔)
    • 有效(ENUM:y,n)
    • Currently_available_for_sale(ENUM:y,n)
    • style_type_id
    • date_active(DATETIME)
  • subsite_style_alias
    • style_id
    • 显示
    • subsite_logo_group_id
    • subsite_id(INT)

记录类似于

  • jstyle_category
    • 1234,27,572,0,y
    • 8800,27,572,1,y
    • 8800,23,953,0,y
    • 8500,23,572,0,y
  • 风格
    • 1234,572,y,y,99,0000-00-00
    • 8800,123,y,y,99,0000-00-00
    • 8500,572,y,y,99,0000-00-00
  • subsite_style_alias
    • 8800,0,y,2589,572
    • 8800,1,y,3475,572
    • 8800,1,y,9554,368

我需要一个包含jstyle_category中所有项目的子集,其中category_id = 27,其中包含来自subsite_style_alias的数据(如果存在的话,这部分我用以下查询完成)。我的真正问题是目前我得到的东西是:

  • 27,0,1234,NULL,NULL
  • 27,0,8800,0,2589
  • 27,1,8800,1,3475

我需要的是8800,其中没有相应的subsite_style_alias,因此最终结果将是

  • 27,0,1234,NULL,NULL
  • 27,1,8800,NULL,NULL
  • 27,0,8800,0,2589
  • 27,1,8800,1,3475

我知道我接近答案,我无法弄清楚。

我也试图尽可能避免使用联合,而是使用相同表的连接

SELECT  jstyle_category.category_id category_id,
    jstyle_category.sort_order category_pos,
    style.id style_id,
    subsite_style_alias.pos pos,
    subsite_style_alias.subsite_logo_group_id
FROM  `jstyle_category` 
    LEFT JOIN style ON style.id = jstyle_category.style_id
    LEFT JOIN subsite_style_alias ON style.id = subsite_style_alias.style_id AND subsite_style_alias.subsite_id = 572
WHERE 
(

    (
        style.subsite_id = ""  OR 
        FIND_IN_SET("0",style.subsite_id) OR 
        FIND_IN_SET("572",style.subsite_id)
    ) AND 

    (
        subsite_style_alias.`active` = "y"  OR 
        subsite_style_alias.`active` IS NULL 
    ) AND 
    style.active = "y"  AND 
    style.currently_available_for_sale = "y"  AND 
    style.style_type_id NOT IN (7,10,11)  AND 
    jstyle_category.category_id = 27  AND 
    jstyle_category.subsite_id IN (0,572)  AND 
    jstyle_category.active = "y"  AND 

    (
        style.date_active IS NULL  OR 
        style.date_active <= "2012-02-24 18:00:00" 
    )
)
GROUP BY subsite_style_alias.subsite_logo_group_id,
    style.id
ORDER BY category_pos, subsite_style_alias.pos IS NULL,
    subsite_style_alias.pos,
    style.id

谢谢

3 个答案:

答案 0 :(得分:0)

LEFT JOIN更改为LEFT OUTER JOIN

请参阅this reference on outer joins in MySQL

答案 1 :(得分:0)

我能够使用带有表格的LEFT JOIN以及我称之为NULL表格的方式来执行此操作:

FROM mytab
   LEFT JOIN (
      (SELECT field1, field2, field3 FROM table) UNION (SELECT NULL, NULL, NULL)
   ) tmp_table ON mybab.field = tmp_table.field1

我不想使用UNIONS,但这是我在必须使用多个表格进行UNION时能够找到的最有效方式

答案 2 :(得分:0)

我通过添加一个由NULL形成的新表来解决,然后在WHERE中添加额外的逻辑