将MySql视图更改为select语句

时间:2017-04-11 15:32:59

标签: mysql

我有一个名为wallcitiescouncils的视图,以及一个从此视图返回值的过程。 我需要更快的respose,所以我想将这个View改为Select语句,但暂时没有成功。

我需要两个表格,城市和议会的结果,这是我的查看代码:

CREATE OR REPLACE VIEW wallcitiescouncils AS
SELECT
    concat('p',cities.id) as id,
    cities.name as name,
    cities.country_id,
    concat(cities.name,' (',councils.name,'), ',states.name,', ',countries.name) as fullname,
    'City' as type

FROM cities
    JOIN countries  ON (cities.country_id = countries.id)
    JOIN states     ON (cities.state_id = states.id)
    JOIN councils   ON (cities.council_id = councils.id)

UNION ALL

SELECT
    concat('c',councils.id) as id,
    councils.name as name,
    councils.country_id,
    concat(councils.name,'(Council)') as fullname,
    'Council' as type

FROM councils

这是我的程序:

BEGIN
  SELECT name as city, id as city_id, fullname
  FROM wallcitiescouncils
  WHERE country_id = _country_id AND name LIKE CONCAT(search , '%') ORDER BY name LIMIT _limit;
END

我需要使用Select语句更改FROM wallcitiescouncils,这样我就不必调用View。

这是我的尝试之一,但结果不正确(我没有议会结果,'fullname'总是得到相同的议会名称),我使用councils_id(仅出现在城市表中)试图了解如果是城市或城市的话:

SELECT
    if(
        cities.council_id is null,
        concat('c',councils.id),
        concat('p',cities.id)
        ) as id,
    if(
        cities.council_id is null,
        councils.name,
        cities.name
        ) as name,

    if(
        cities.council_id is null,
        councils.country_id,
        cities.country_id
        ) as country_id,
    if(
        cities.council_id is null,
        concat(councils.name,' (Municipio)'),
        concat(cities.name,' (',councils.name,'), ',states.name,', ',countries.name)
        )  as fullname
FROM councils, cities
    JOIN countries  ON (country_id = countries.id)
    JOIN states     ON (state_id = states.id)
    /*JOIN councils   ON (cities.council_id = councils.id)*/
where cities.id = 1 or councils.id = 1 limit 200

1 个答案:

答案 0 :(得分:1)

首先尝试此查询 -

SELECT name as city, id as city_id, fullname FROM (
  SELECT
    concat('p',cities.id) as id,
    cities.name as name,
    cities.country_id,
    concat(cities.name,' (',councils.name,'), ',states.name,', ',countries.name) as fullname,
    'City' as type

  FROM cities
    JOIN countries  ON (cities.country_id = countries.id)
    JOIN states     ON (cities.state_id = states.id)
    JOIN councils   ON (cities.council_id = councils.id)

  UNION ALL

  SELECT
    concat('c',councils.id) as id,
    councils.name as name,
    councils.country_id,
    concat(councils.name,'(Council)') as fullname,
    'Council' as type
  FROM councils
  ) v
WHERE
  v.country_id = _country_id AND v.name LIKE CONCAT(search , '%') ORDER BY v.name LIMIT _limit;