什么是替代MySQL中的视图?

时间:2019-02-01 07:06:58

标签: php mysql

我在下面查询,结果是什么并不重要

SELECT
    `doctors`.`id` AS `id`,
    `doctors`.`name` AS `name`,
    count( `onvan-naghs`.`negative-mark` ) AS `negative_marks` 
FROM
    (
    (
    (
    ( `doctors` JOIN `doctor-barge-naghs` ON ( ( `doctor-barge-naghs`.`code-doctor` = `doctors`.`id` ) ) )
    JOIN `onvan-naghs` ON ( ( `doctor-barge-naghs`.`code-naghs` = `onvan-naghs`.`id` ) ) 
    )
    JOIN `barge` ON ( ( `doctor-barge-naghs`.`code-barge` = `barge`.`id` ) ) 
    )
    JOIN `paziresh` ON ( ( `barge`.`shomare-paziresh` = `paziresh`.`id` ) ) 
    ) 
WHERE
    ( `paziresh`.`tarikh_paziresh` BETWEEN 1111111111 AND 9999999999 ) 
GROUP BY
    `doctors`.`id`,
    `doctors`.`name` 
ORDER BY
    `onvan-naghs`.`negative-mark` DESC

然后将其另存为名为scores的视图 然后在另一个查询中使用它,效果很好

SELECT
    `scores`.`id` AS `id`,
    `scores`.`name` AS `name`,
    `scores`.`negative_marks` AS `negative_marks`,
    find_in_set( `scores`.`negative_marks`, ( SELECT group_concat( DISTINCT `scores`.`negative_marks` ORDER BY `scores`.`negative_marks` DESC SEPARATOR ',' ) FROM `scores` ) ) AS `rank` 
FROM
    `scores`

但是我的问题是在某些情况下我无法使用视图 我想使用整个查询,而我必须使用子查询 但是我不能在它外面使用子查询 像下面一样

SELECT *,
    find_in_set( `t1`.`negative_marks`, ( SELECT group_concat( DISTINCT `t1`.`negative_marks` ORDER BY `t1`.`negative_marks` DESC SEPARATOR ',' ) FROM `t1` ) ) AS `rank` 
FROM
(
SELECT
    `doctors`.`id` AS `id`,
    `doctors`.`name` AS `name`,
    count( `onvan-naghs`.`negative-mark` ) AS `negative_marks` 
FROM
    (
    (
    (
    ( `doctors` JOIN `doctor-barge-naghs` ON ( ( `doctor-barge-naghs`.`code-doctor` = `doctors`.`id` ) ) )
    JOIN `onvan-naghs` ON ( ( `doctor-barge-naghs`.`code-naghs` = `onvan-naghs`.`id` ) ) 
    )
    JOIN `barge` ON ( ( `doctor-barge-naghs`.`code-barge` = `barge`.`id` ) ) 
    )
    JOIN `paziresh` ON ( ( `barge`.`shomare-paziresh` = `paziresh`.`id` ) ) 
    ) 
WHERE
    ( `paziresh`.`tarikh_paziresh` BETWEEN 1111111111 AND 9999999999 ) 
GROUP BY
    `doctors`.`id`,
    `doctors`.`name` 
ORDER BY
    `onvan-naghs`.`negative-mark` DESC
    ) as t1

它无法使用t1并了解它的含义,并说“表'client-hospital.t1'不存在”

当我想使用整个查询而不是拥有不同的视图并且子查询不能在外部使用时该怎么办?

我尝试使用语法,但平台不支持该语法 我需要下面的代码

WITH
  cte1 AS (SELECT a, b FROM table1),
  cte2 AS (SELECT c, d FROM table2)
SELECT b, d FROM cte1 JOIN cte2
WHERE cte1.a = cte2.c;

例如,想象下图 an example 为什么我找不到这样的方法为什么不能以这种方式使用子查询,我想得到答案

0 个答案:

没有答案