我已经尝试找出这个查询几个小时了,但没有成功。

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

这些表具有以下架构:


jstyle_category:

style_id
category_id
subsite_id(INT)
排序
有效(ENUM:y,n)

样式

ID
subsite_id(STRING,逗号分隔)
有效(ENUM:y,n)
current_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


我知道我已经接近答案了,我只是想不通。

我还尝试尽可能避免使用Union,而是使用相同表的联接

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


谢谢

最佳答案

LEFT JOIN更改为LEFT OUTER JOIN

请参见this reference on outer joins in MySQL

09-06 15:35