如何在 select all (*) 中为视图 SQL 创建子查询?

How make a subquery in a select all (*) for a view SQL?

我想制作一个包含多个 table 的视图,但我需要的是 select * from 一个 table 和 select table秒。这是我到目前为止所拥有的:

CREATE VIEW `database`.`pages_view` AS
SELECT
    `p`.`p_name` AS `p_name`,
    `p`.`slug` AS `slug`,
    `i`.`image` AS `image`,
    `t`.`title` AS `title`,
    `t`.`text` AS `text`,
    `s`.`sec_name` AS `sec_name`
FROM
    (((`database`.`pages` `p`
    LEFT JOIN `database`.`page_image` `i` ON ((`p`.`id` = `i`.`pages_id`)))
    LEFT JOIN `database`.`page_text` `t` ON ((`p`.`id` = `t`.`pages_id`)))
    LEFT JOIN `database`.`sections` `s` ON ((`p`.`id` = `t`.`pages_id`)))
WHERE
    (`p`.`visible` = 1)

我要的是select * from sections而不是一一调用

只需使用 s.*:

CREATE VIEW database.pages_view AS
    SELECT p.p_name, p.slug, i.image, t.title, t.text,
           s.*
    FROM database.pages p LEFT JOIN 
         database.page_image i
         ON p.id = i.ages_id LEFT JOIN 
         database.page_text t
         ON p.id = t.pages_id LEFT JOIN
         database.sections s
         ON p.id = t.pages_id
    WHERE p.visible = 1;

备注:

  • 您不需要转义字符(除非您的 table 或列名称不当)。
  • 对于 table 别名尤其如此。
  • 您不需要将列重命名为相同的名称p.p_name as p_name 是多余的 -- 不值得额外输入。

此外,在视图中使用 * 时要小心。这是您问题的答案,但列的名称、类型和顺序取决于基础 table.