我在连接选择中有多个表。其中一个表是一个对“事物”的评论列表。用户已完成。他们基本上给它一些明星。 1至5。
两个主要表格:
地方
id INT
name VARCHAR(128)
评论
review_id INT
welcome INT
hospitality INT
condition INT
示例查询:
select p.name, r.welcome, r.hospitality, r.condition from places p
join reviews r on p.id = r.review_id
name nameA
welcome 1
hospitality 3
condition 4
我有一个单独的表(review_descriptors),其中包含了例如星号数量的描述符。
1: bad
2: ok
3: good
4: very good
5: excellent
因此,第一个查询的典型行,所有连接可以是:
name welcome hospitality condition
nameA 1 3 4
但我希望返回的数据是:
name welcome hospitality condition
nameA bad good very good
描述符表
review_num INT // this will match against the value of welcome, hospitality, condition
description VARCHAR(32)
我不认为我可以简单地加入每行多个字段
另外,如果我想稍后全局更改评论描述符,我宁愿不解析表格中的数据
有办法做到这一点吗?根据主要的查询结果,它几乎就像是反向查找
答案 0 :(得分:0)
如果我理解你的数据结构,那么条件聚合会做你想要的吗?
select p.name,
max(case when r.name = 'welcome' then d.description end) as welcome,
max(case when r.name = 'hospitality' then d.description end) as hospitality,
max(case when r.name = 'condition' then d.description end) as condition,
from places p join
reviews r
on p.id = r.id join
review_descriptors d
on r.numstars = d.numstars
group by p.name;
编辑:
另一方面,如果结果已经转动,则需要多个连接:
select p.*, dw.description as welcome, dh.descrption as hospitality,
dc.condition as condition
from places p join
reviews r
on p.id = r.id left join
review_descriptors dw
on r.welcome = dw.numstars lef tjoin
review_descriptors dh
on r.hospitality = dh.numstars lef tjoin
review_descriptors dc
on r.condition = dc.numstars