简体   繁体   中英

MySQL: [Err] 1146 - table 'alias' doesn't exist

I'm looking for something like

SELECT
    `foo`.*,
    (SELECT MAX(`foo`.`bar`) FROM `foo`)
FROM
    (SELECT * FROM `fuz`) AS `foo`;

but it seem that foo does not get recognized in nested query as there is error like

[Err] 1146 - Table 'foo' doesn't exist

I try the query above because I think its faster than something like

SELECT
    `fuz`.*,
    (SELECT MAX(`bar`) FROM `fuz`) as max_bar_from_fuz
FROM `fuz`

Please give me some suggestions.

EDIT: I am looking for solutions with better performance than the second query. Please assume that my table fuz is a very, very big one, thus running an additional query getting max_bar cost me a lot.

What you want, for the first query (with some modification) to work, is called Common Table Expressions and MySQL has not that feature.

If your second query does not perform well, you can use this:

SELECT
    fuz.*,
    fuz_grp.max_bar
FROM 
    fuz
  CROSS JOIN
    ( SELECT MAX(bar) AS max_bar
      FROM fuz
    ) AS fuz_grp

Alias created into a SELECT clause only can be used to access scalar values, they are not synonyms to the tables. If you want to return the max value of a column for all returned rows you can do it by running a query before to calculate the max value into a variable and then use this variable as a scalar value into your query, like:

-- create and populate a table to demonstrate concept
CREATE TABLE fuz (bar INT, col0 VARCHAR(20), col1 VARCHAR(20) );
INSERT INTO fuz(bar, col0, col1) VALUES (1, 'A', 'Airplane');
INSERT INTO fuz(bar, col0, col1) VALUES (2, 'B', 'Boat');
INSERT INTO fuz(bar, col0, col1) VALUES (3, 'C', 'Car');

-- create the scalar variable with the value of MAX(bar)
SELECT @max_foo:=MAX(bar) FROM fuz;

-- use the scalar variable into the query
SELECT *, @max_foo AS `MAX_FOO`
FROM fuz;

-- result:
-- | BAR | COL0 |     COL1 | MAX_FOO |
-- |-----|------|----------|---------|
-- |   1 |    A | Airplane |       3 |
-- |   2 |    B |     Boat |       3 |
-- |   3 |    C |      Car |       3 |

Just simple use MAX function:

SELECT
    `fuz`.*,
    MAX(`fuz`.`bar`)
FROM
    `fuz`

or if you use

SELECT
    `foo`.*,
    MAX(`foo`.`bar`)
FROM
    (SELECT * FROM `fuz` JOIN `loolse' ON (`fuz`.`field` = `loolse`.`smile`)) AS `foo`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM