操作数应包含1列但在子查询中需要max(value)

时间:2013-01-15 09:39:38

标签: php mysql sql

我需要将MySql数据库导出到SQLite数据库,我只从medias获取所需的数据,以使de SQLite数据库变得更小。

我有一个查询仅向我提供与最新版本,已发布且未归档动物或植物的条目相关的animalsMedias或植物媒体。

SELECT AM.*, max(A.version) AS version FROM animalsMedias AS AM INNER JOIN animals
AS A ON(AM.idAnimal = A.idAnimal AND A.filed = 0 AND A.published = 1) GROUP BY 
A.idLanguaje, A.idVersion;

为了获得相关的媒体,我尝试在" medias"上进行选择。只返回与前一个select的结果相关的媒体的表,所以我把它们都放在" IN()"中,但我得到错误:

#1241 - Operand should contain 1 column(s)

这是查询:

SELECT * from medias 
WHERE idMedia IN(SELECT AM.*, max(A.version) AS version FROM
animalsMedias AS AM 
INNER JOIN animals AS A ON(AM.idAnimal = A.idAnimal AND A.filed = 0 
AND A.published = 1) 
GROUP BY A.idLanguaje, A.idVersion) 
OR idMedia IN(SELECT PM.*, max(P.version) AS version FROM plantsMedias AS PM 
INNER JOIN plants AS P ON(PM.idPlant = P.idPlant AND P.filed = 0 AND P.published = 1) 
GROUP BY P.idLanguaje, P.idVersion);

我如何获得" max(A.version)"如果我必须只使用1个操作数?如果我理解为好,在IN里面我必须只有" IN(选择AM.idMedia FROM ...."是正确的。

感谢您的建议,对不起我的英语,我会尽我所能。

1 个答案:

答案 0 :(得分:2)

JOIN表而不是这些IN谓词:

SELECT 
  ....
  A.version AVersion,
  P.Version PVersion
FROM medias m
INNER JOIN animalsMedias AS AM  ON m.idMedia = am.Id
INNER JOIN plantsMedias  AS PM  ON m.idMedia = PM.ID
LEFT JOIN
(
  SELECT idAnimal, max(A.version) AS version 
  FROM animals
  WHERE A.filed = 0 
    AND A.published = 1     
  GROUP BY A.idLanguaje, A.idVersion 
) AS  A  ON AM.idAnimal = A.idAnimal 
LEFT JOIN
(
  SELECT idPlant, MAX(Version) version
  FROM Plants
  WHERE field = 0 AND published = 1
  GROUP BY P.idLanguaje, P.idVersion
) AS p ON PM.idPlant = P.idPlant;