我有一个非常大的模特,有许多人,很多人,很多人。关系。 我使用许多表创建一个View以获得更好的搜索结果,但仍然无法在一个字段中加载数据透视表中的所有值。
我有什么:
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)
我想要的(伪代码)
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.*
(SELECT all istallations from installations) as installations //and get all values from pivot table
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)
JOIN estates_intallations ON (estates.id = estates_installations.estate_id) // this is the pivot table
进入"装置"以任何格式填写所有ID:
instatallations内容可能是:
instatallations => " 1 4 7 15"或" [1,4,7,15]"等等。
我可以用PHP来做,但我需要使用一个查询,避免使用数千个查询来创建此视图。
(最近被问到但可能让它无法理解)
答案 0 :(得分:1)
用
替换子查询( SELECT GROUP_CONCAT(inst_num)
FROM installations AS i
WHERE i... = ... ) AS installations
对于inst_num
使用任何列给你1,4等。
对于i...=...
,使用任何条件将`安装绑定到其他表。
(你错过了一个逗号。)
答案 1 :(得分:0)
感谢Rick James。对于任何有相同问题的人(对SQL的经验很少),我想完成答案。 想象一下,我们必须使用表,Estates主表和一个名为estates_extras的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,我们将在我们的视图中重复相同数量的列,因为元素具有额外内容,在此示例中(有三个附加内容):
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
如果我们没有将JOIN添加为LEFT JOIN,那么我们没有结果没有几乎没有额外的Estates。所以,对于这个查询,我们将拥有我们所有的Estates,如果他们有额外的,则以逗号分隔的列表。
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)