在MySQL的一个字段中创建一个包含透视表中所有值的视图
我有一个非常大的模型,有很多“多对多”的关系。 为了获得更好的搜索结果,我使用多个表创建了一个视图,但仍然无法在一个字段中加载透视表中的所有值 我所拥有的:在MySQL的一个字段中创建一个包含透视表中所有值的视图,mysql,view,pivot-table,Mysql,View,Pivot Table,我有一个非常大的模型,有很多“多对多”的关系。 为了获得更好的搜索结果,我使用多个表创建了一个视图,但仍然无法在一个字段中加载透视表中的所有值 我所拥有的: CREATE OR REPLACE VIEW westates AS SELECT concat(estates.locale,estates.id) as code, cities.name as city, councils.name as
CREATE OR REPLACE VIEW westates AS
SELECT
concat(estates.locale,estates.id) as code,
cities.name as city,
councils.name as council,
states.name as state,
countries.name as country,
concat(cities.name,' (',councils.name,')') as city_council,
estates.*
FROM estates
JOIN countries ON (estates.country_id = countries.id)
JOIN states ON (estates.state_id = states.id)
JOIN councils ON (estates.city_council_id = councils.id)
JOIN cities ON (estates.city_id = cities.id)
我想要的(伪代码)
并在“安装”字段中以任何格式获取所有ID:
安装内容可以是:
installations=>“14 7 15”或“[1,4,7,15]”等
我可以用PHP来实现,但我需要使用一个查询来避免使用数千个查询来创建此视图
(最近询问,但可能使其无法压缩)将子查询替换为
( SELECT GROUP_CONCAT(inst_num)
FROM installations AS i
WHERE i... = ... ) AS installations
对于inst_num
使用任何列给出的1,4等值。对于
i..=…
使用将安装与其他表关联的任何条件
(你缺少了一个逗号。)多亏了里克·詹姆斯。对于任何有同样问题的人(几乎没有SQL经验),我想完成答案。 想象一下,我们必须创建一个表、一个主表和一个数据透视表,其中包含一些名为Estates\u Extras的额外数据
table estates
columns id, address
table estates_extras
columns estate_id, extra_id
我们需要一个具有以下内容的视图:
table westates
columns estates.id, estates.address, extras
like
id address extras
25000 My nice road 1,5,8
首先:
如果我们不包括DISTINCT,我们将在我们的视图中重复相同数量的列,就像本例中的extras中的元素一样(有三个extras):
如果我们不将连接添加为左连接,那么对于几乎没有一个额外连接的地产,我们就没有结果。所以,通过这个查询,我们将拥有我们所有的不动产,如果他们有额外的,一个逗号分隔的列表
CREATE OR REPLACE VIEW westates AS
SELECT DISTINCT
estates.id,
estates.address,
(SELECT GROUP_CONCAT(estates_extras.extras_id) FROM estates_extras
WHERE estates_extras.estate_id = estates.id ) AS extras
FROM estates
LEFT JOIN estates_extras ON (estates_extras.estates_id = estates.id)
results
id address extras
25000 My nice road 1,5,8
25000 My nice road 1,5,8
25000 My nice road 1,5,8
CREATE OR REPLACE VIEW westates AS
SELECT DISTINCT
estates.id,
estates.address,
(SELECT GROUP_CONCAT(estates_extras.extras_id) FROM estates_extras
WHERE estates_extras.estate_id = estates.id ) AS extras
FROM estates
LEFT JOIN estates_extras ON (estates_extras.estates_id = estates.id)