MySQL Unknown列on子句

时间:2013-06-20 00:12:17

标签: mysql sql

第一个查询正在运行:

SELECT video.seller from video;

第二个不是:

SELECT SQL_CALC_FOUND_ROWS *,
       t.name as tname
FROM video, type as t 
INNER JOIN user 
ON video.seller = user.id 
WHERE video.type2 = t.id 
AND thumbnail_blobKey != '' 
AND disabled = 0 
AND is_reel = 0 
AND price!= 0 
AND video.type != 4  
GROUP BY video.id 
ORDER BY video.id DESC LIMIT 0, 10
  

错误:未知栏' video.seller'在' on条款'

2 个答案:

答案 0 :(得分:3)

这是一个有趣的例子。格式更好:

SELECT SQL_CALC_FOUND_ROWS *, t.name as tname
FROM video, type as t INNER JOIN
     user
     ON video.seller = user.id
WHERE video.type2 = t.id AND
     thumbnail_blobKey != '' AND disabled = 0 AND is_reel = 0 AND price!= 0 AND video.type != 4 
GROUP BY video.id
ORDER BY video.id DESC
LIMIT 0, 10

问题是由于videofrom子句的其余部分无法理解,的列。这就是逗号的工作原理。有趣的是,只需将,替换为逻辑等效cross join即可解决此问题:

SELECT SQL_CALC_FOUND_ROWS *, t.name as tname
FROM video cross join type as t INNER JOIN
     user
     ON video.seller = user.id
WHERE video.type2 = t.id AND
     thumbnail_blobKey != '' AND disabled = 0 AND is_reel = 0 AND price!= 0 AND video.type != 4 
GROUP BY video.id
ORDER BY video.id DESC
LIMIT 0, 10

这在documentation中有解释,原因是优先顺序。逗号的优先级低于cross join。因此,表达式中的连接被评估为“视频连接(类型连接用户)”。由于首先解释了第二个连接,因此video中的列不可知。

但是,表上确实有一个连接,所以最好写成:

SELECT SQL_CALC_FOUND_ROWS *, t.name as tname
FROM video join
     type t
     on video.type2 = t.id INNER JOIN
     user
     ON video.seller = user.id
WHERE thumbnail_blobKey != '' AND disabled = 0 AND is_reel = 0 AND price!= 0 AND video.type != 4 
GROUP BY video.id
ORDER BY video.id DESC
LIMIT 0, 10

答案 1 :(得分:1)

正如现在所写的那样,您正在尝试加入表格typeuser,其条件为video.seller = user.id。由于video.seller是一个表typeuser的列,因此您有错误。

更改为以下内容将删除此错误:

    SELECT SQL_CALC_FOUND_ROWS *,
       t.name AS tname
FROM video
INNER JOIN USER ON video.seller = USER.id,
                                       TYPE AS t
WHERE video.type2 = t.id
  AND thumbnail_blobKey != ''
  AND disabled = 0
  AND is_reel = 0
  AND price!= 0
  AND video.TYPE != 4
GROUP BY video.id
ORDER BY video.id DESC LIMIT 0,
                             10