在JOIN-ON / WHERE中无法识别子查询表别名

时间:2018-08-10 19:11:29

标签: mysql outer-join table-alias

我正在尝试通过SQL Server经验为MySQL的爱好者提供一些帮助。

他正在研究游戏数据库。我为他写了这个查询

SELECT ib.itemid, ii.realname as name, ib.stackSize,
       IFNULL(ah.price, '-') as price, ah.stock
    FROM item_basic ib
    LEFT OUTER JOIN item_info as ii ON ii.itemID = ib.itemID
    LEFT OUTER JOIN (SELECT price, COUNT(*) as stock
        FROM auction_house
        GROUP BY itemID) as AH on ii.itemID = AH.itemID -- erring line
    ORDER BY ii.realname

一个用于将子查询组装在FROM子句中而不是JOIN中的版本,但是没有此版本麻烦。

这给出了错误 Unknown column 'ah.itemID' in 'on clause'

如果我错误地将错误行更改为... ii.itemID = ib.itemID,则会执行查询,但是结果当然是不正确的(在这种情况下,指数增加了一倍)。

这是带有示例数据的 SQL Fiddle

2 个答案:

答案 0 :(得分:1)

没有AH.itemID,您只能访问子查询的结果。

答案 1 :(得分:1)

这是因为您没有在子查询中选择itemID。此外,您在选择价格列时未对其进行汇总。尝试更换

#!/usr/bin/env perl
# unique_random.pl : get N non-repeating random numbers from list
use strict;
use warnings;
use feature qw(say);
use Tie::File;
use List::Util qw(shuffle);

# get the number of values to print from command line
my $n = shift @ARGV;
$n = defined($n) ? int($n) : 10;
if ($n < 1 or $n > 100) { # sanity check
   $n = 10;
}

# persistent file of shuffled numbers tied to an array
my $file = 'random_numbers.txt';
tie my @numbers, 'Tie::File', $file or die "Can't tie $file";

# initialize the array if it's empty or not full enough
if ( scalar(@numbers) <= $n ) {
    @numbers = shuffle (1000 .. 99999); # all 4 and 5 digit numbers
}

# get the first $n numbers and delete them from the array
for ( 1 .. $n ) {
   say shift @numbers;
}

使用

LEFT OUTER JOIN (SELECT price, COUNT(*) as stock
        FROM auction_house
        GROUP BY itemID) as AH on ii.itemID = AH.itemID