我一直试图弄清楚这个查询几个小时但没有成功。
我有3张桌子: - jstyle_category - 风格 - subsite_style_alias
表格有这个模式:
记录类似于
我需要一个包含jstyle_category中所有项目的子集,其中category_id = 27,其中包含来自subsite_style_alias的数据(如果存在的话,这部分我用以下查询完成)。我的真正问题是目前我得到的东西是:
我需要的是8800,其中没有相应的subsite_style_alias,因此最终结果将是
我知道我接近答案,我无法弄清楚。
我也试图尽可能避免使用联合,而是使用相同表的连接
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
谢谢
答案 0 :(得分:0)
将LEFT JOIN
更改为LEFT OUTER JOIN
。
答案 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中添加额外的逻辑