2013-04-28 61 views
1

我试图创建一个用户收藏夹系统,但创建一个查询完成我所需要的困难时间。我将以水果为例。MySQL三表加入用户收藏夹系统

首先,这是我fruitsinfo表:

 id  | color | rating 
     apples  red   8.4 
     oranges  orange  9.1 
    blueberries  blue   8.8 
    pineapple  yellow  7.9 
     peaches  orange  8.3 

然后是表,该表只列出水果的季节,有他们的当前市场价格(这个数据是欢快的不好,但我承担) :

 id  | price | months left in season 
    apples   1.25   6 
    avocados  1.42   4 
    pears   1.24   3 
    oranges  1.75   5 
    blueberries 2.20   4 

最后,userfavorites表,其中包含的用户名和水果ID:

 userid | fruitid 
     5   apples 
     5   peaches 
     5   pears 

我们将与userid ='5'的用户一起工作。有几件事要注意这里:并非currentfruits中的所有条目都在fruitsinfo中,并非userfavorites中的所有条目都在currentfruits中。

当用户通常访问该网站没有收藏保存的,他们只看到currentfruits左侧加入了与fruitsinfo和价格排序,像这样:

id  | price | months left in season | color | rating 
blueberries 2.20     4    blue 8.8 
    oranges  1.75     5    orange 9.1 
    avocados 1.42     4    null null 
    apples  1.25     6    red  8.4 
    pears  1.24     3    null null 

现在,我要的是为了有一个检查用户最喜欢的水果是否在currentfruits表中,然后列出这些结果(按价格排序),然后列出其他当前水果(按价格排序)。我们的用户有苹果,梨,并为收藏桃子,但只有苹果和梨是currentfruits,所以表现在应该是这样的:

id  | price | months left in season | color | rating 
    apples  1.25     6    red  8.4 
    pears  1.24     3    null null 
blueberries 2.20     4    blue 8.8 
    oranges  1.75     5    orange 9.1 
    avocados 1.42     4    null null 

我最初的想法是做这样的事情:

SELECT * 
FROM userfavorites 
JOIN currentfruits ON userfavorites.fruitid = currentfruits.id 
JOIN fruitsinfo ON currentfruits.id = fruitsinfo.id 
ORDER BY currentfruits.price DESC 

UNION 

SELECT * 
FROM currentfruits 
LEFT JOIN fruitsinfo ON currentfruits.id = fruitsinfo.id 
ORDER BY currentfruits.price DESC 

第一个SELECT抓取所需表格的前两行,第二个抓取整个表格,用户将看到没有收藏夹的整个表格。不幸的是,这并不仅仅是像我希望的那样把整排排队。另外,因为UNION只处理不同的条目,所以我希望能够处理可能与底部选择一起显示的重复行,但可惜。

任何人都可以告诉我如何可以去做一个查询,完成我想要做的事情吗?谢谢。

回答

3

您不必使用UNION。试试:

select c.id, c.price, c.`months left in season`, i.color, i.rating 
from currentfruit c 
left join fruitsinfo i on c.id = i.id 
left join userfavorites f on c.id = f.id and f.userid = 5 
order by case when f.id is not null then 0 else 1 end, c.price desc