我正在尝试创建一个用户收藏夹系统,但很难创建一个可以完成我需要的查询。我将以水果为例。
首先,这是我的fruitsinfo
表:
id | color | rating
apples red 8.4
oranges orange 9.1
blueberries blue 8.8
pineapple yellow 7.9
peaches orange 8.3
然后是 currentfruit
表,它只列出了时令水果和当前市场价格(这个数据非常糟糕,但请耐心等待):
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和fruit 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
表中是否有用户最喜欢的水果,然后首先列出这些结果(按价格排序),然后是其余的当前水果的数量(按价格排序)。我们的用户最喜欢苹果、梨和桃子,但当前水果中只有苹果和梨,所以表格现在应该如下所示:
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
获取所需表格的前两行,第二个 SELECT
获取用户在没有收藏夹的情况下会看到的整个表格。不幸的是,这并没有像我希望的那样把行撞在一起。另外因为 UNION 只处理不同的条目,我希望它能处理可能出现在底部选择中的重复行,但可惜。
谁能告诉我如何进行查询来完成我想做的事情?谢谢。
最佳答案
您不必使用 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
关于用户收藏夹系统的MySQL三表连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16262056/