添加第四个表连接时结果减少

时间:2012-04-05 16:30:58

标签: mysql database join

编辑:现在出于某种原因,每个productid只出现一次而不是取决于它有多少变化?有任何想法吗? (我使用的查询是我列出的最后一个查询)

这是我的三个表连接查询

SELECT xp.productid, xp.product, xc.classid, xco.optionid, xco.option_name
FROM xcart_products xp
JOIN xcart_classes xc ON xp.productid = xc.productid and xc.class = 'Color'
JOIN xcart_class_options xco ON xc.classid = xco.classid
ORDER by xp.product DESC

现在这里的一切都很棒,我得到大约2,000个结果,一切都井然有序。

现在我想添加第四个表来运行每个xi.id的xi.optionid数量的计数,但由于某种原因,我只得到大约200个结果并且无法找出原因。这是我试图运行的查询

SELECT xp.productid, xp.product, xc.classid, xco.optionid, xco.option_name, count(xi.optionid) as cnt
    FROM xcart_products xp 
    INNER JOIN xcart_classes xc ON xp.productid = xc.productid AND xc.class = 'Color'
    INNER JOIN xcart_class_options xco ON xc.classid = xco.classid 
    INNER JOIN xcart_images_D xi ON xi.optionid = xco.optionid
    GROUP BY xp.product
    ORDER by xp.product DESC

以下是每个表的基本架构

xcart_products -
    + productid*
    + product
xcart_classes - 
    + classid*
    + productid (xcart_products.productid)
xcart_class_options -
    + optionid*
    + classid (xcart_classes.classid)
    + option_name
xcart_images_D - 
    + imageid*
    + optionid (xcart_class_options.optionid)
    + id (xcart_products.productid)

我正在使用的查询 -

SELECT xp.productid, xp.product, xc.classid, xco.optionid, xco.option_name, count(xi.optionid) as cnt
FROM xcart_products xp
JOIN xcart_classes xc ON xp.productid = xc.productid AND xc.class = 'Color'
JOIN xcart_class_options xco ON xc.classid = xco.classid
LEFT JOIN xcart_images_D xi ON xi.optionid = xco.optionid
GROUP BY xp.product 
ORDER by xp.product DESC

2 个答案:

答案 0 :(得分:1)

请尝试使用LEFT OUTER JOIN

select xp.productid,
    xp.product,
    xc.classid,
    xco.optionid,
    xco.option_name,
    count(xi.optionid) as cnt
from xcart_products xp
inner join xcart_classes xc on xp.productid = xc.productid
    and xc.class = 'Color'
inner join xcart_class_options xco on xc.classid = xco.classid
left outer join xcart_images_D xi on xi.optionid = xco.optionid
group by xp.product
order by xp.product desc

答案 1 :(得分:1)

用户在最后一张桌子上进行左连接。