如何在子查询中访问列?

时间:2013-09-10 11:39:31

标签: mysql sql subquery union

我遇到以下问题的问题。对于返回总结果总和的子查询,我在'where子句'中收到错误未知列'search.term',我不知道我怎么能这样做查询得当吗?任何帮助表示赞赏。

SELECT *,
  (SELECT SUM(totalResults)
   FROM (SELECT COUNT(*) as totalResults
         FROM media
         LEFT JOIN users ON users.id = media.userId
         WHERE media.title LIKE CONCAT('%', search.term, '%')
       OR media.description LIKE CONCAT('%', search.term, '%')
       OR media.tags LIKE CONCAT('%', search.term, '%')
       OR users.username LIKE search.term
         UNION ALL
         SELECT COUNT(*)
         FROM reposts
         LEFT JOIN media ON media.id = reposts.mediaId
         LEFT JOIN users ON users.id = reposts.userId
         WHERE media.title LIKE CONCAT('%', search.term, '%')
       OR media.description LIKE CONCAT('%', search.term, '%')
       OR media.tags LIKE CONCAT('%', search.term, '%')
       OR users.username LIKE search.term
         )
  t) AS totalResults,
  MAX(search.timestamp) AS searchTimestamp
  FROM search
  WHERE userId = '1'
  GROUP BY search.term
  ORDER BY searchTimestamp DESC

1 个答案:

答案 0 :(得分:2)

原因是双嵌套SELECT子查询。试试这个:

 SELECT  term,
         ( SELECT COUNT(*)
           FROM media
           LEFT JOIN users ON users.id = media.userId
           WHERE media.title LIKE CONCAT('%', search.term, '%') 
              OR media.description LIKE CONCAT('%', search.term, '%') 
              OR media.tags LIKE CONCAT('%', search.term, '%') 
              OR users.username LIKE search.term
         )
         +
         ( SELECT COUNT(*)
           FROM reposts
           LEFT JOIN media ON media.id = reposts.mediaId
           LEFT JOIN users ON users.id = reposts.userId
           WHERE media.title LIKE CONCAT('%', search.term, '%') 
              OR media.description LIKE CONCAT('%', search.term, '%') 
              OR media.tags LIKE CONCAT('%', search.term, '%') 
              OR users.username LIKE search.term
         ) AS totalResults,
         MAX(timestamp) AS searchTimestamp
FROM search
WHERE userId = '1'
GROUP BY term
ORDER BY searchTimestamp DESC ;

旁注:在SELECT *期间使用GROUP BY <columns>会在除<columns>之外的所有其他列中为您提供不确定的结果。 MySQL允许这种不明确的行为,但这不是一种好的做法。