[英]database redesign or complex 4 way join query
I have an application where a user adds things they've bought to their account. 我有一个应用程序,用户可以将他们购买的商品添加到他们的帐户中。 They create a list name eg my ebay purchaes, then add what they've bought in the past.
他们创建一个列表名称(例如,我的eBay购买),然后添加他们过去购买的商品。
When they create the list they can choose whether its public or not, and this is where i'm struggling. 当他们创建列表时,他们可以选择是否公开,这就是我在努力的地方。
I need to show a list of products and who listed them onto which list, but, if they were listed onto a private list then show the users name as private and the list name as private 我需要显示产品列表以及谁将它们列出到哪个列表中,但是,如果将它们列出到私有列表中,则将用户名显示为私有,将列表名称显示为私有。
4 tables: 4张桌子:
products 制品
prod_id store_name product user_id
------- --------- ------- -------
1 ebay chair 1002
2 amazon desk 1000
3 ebay lamp 1001
users 用户
user_id name
------- -------
1000 john
1001 mark
1002 sue
user_onto_list user_onto_list
user_onto_list_id user_id list_id
------- --------- -------
1 1000 11
2 1001 12
3 1002 10
list_detail list_detail
list_id visibility list_name
------- ------- ---------
10 open myEbayList
11 open myAmazonList
12 private myPrivateList
so the result would be: 因此结果将是:
product listed_by list_name
------- --------- ---------
chair sue myEbayList
desk john myAmazonList
lamp PRIVATE PRIVATE
Is this possible in one query or would you redesign how the data was stored to make it simpler? 是否可以在一个查询中做到这一点,还是您将重新设计数据存储方式以使其更简单? I'd rather keep it like this so if eg sue decided to make her myEbatList private at any time the products would not show as being listed by her and mark may decide to make his list public.
我宁愿这样,所以如果sue例如在任何时候决定将她的myEbatList设为私有,则该产品不会显示为被她列出,并且mark可以决定将其列表公开。
Advice appreciated 意见表示赞赏
select
p.product
, case when ld.visibility = 'private' then
'PRIVATE'
else
u.name
end as listed_by
, case when ld.visibility = 'private' then
'PRIVATE'
else
ld.list_name
end as listed_name
from products p
inner join users u on u.ser_id = p.user_id
inner join user_onto_list uol on uol.user_id = u.user_id
inner join list_detail ld on ld.list_id = uol.list_id
EDIT: I've included the logic regarding privacy in CASE statements as part of the SELECT, as this does not interfere with the JOIN criteria, it's only display information. 编辑:作为选择的一部分,我在CASE语句中包括了有关隐私的逻辑,因为这不会干扰JOIN标准,它仅显示信息。 Alternatively you could build that logic into some kind of UNION structure in a derived table and then join to that, but that would probably be less inefficient.
或者,您可以将该逻辑构建到派生表中的某种UNION结构中,然后加入该结构,但这可能会降低效率。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.