9

我正在尝试创建一个从 MySQL 数据库中选择图像名称的 select 语句。该表称为-pictures_archive。我也在尝试根据它们拥有的类别来选择这些图片。代码是:

SELECT pictures_archive_filename FROM pictures_archive 
WHERE pictures_archive_id = (SELECT pictures_archive_id 
FROM pictures_archive_category WHERE pictures_category_id = 9)

它给了我一个“#1242 - 子查询返回超过 1 行”错误。我知道为什么,但不知道该怎么做。

4

4 回答 4

25

由于您的子查询可以返回多个值,IN因此应该适合您的 where 子句。

SELECT pictures_archive_filename 
FROM pictures_archive 
WHERE pictures_archive_id IN 
(
   SELECT pictures_archive_id 
   FROM pictures_archive_category 
   WHERE pictures_category_id = 9
)

一个替代方案join是更有效的两个表。

SELECT  pictures_archive_filename 
FROM    pictures_archive a 
        INNER JOIN pictures_archive_category b
            ON a.pictures_archive_id = b.pictures_archive_id
WHERE   b.pictures_category_id = 9
于 2012-09-26T08:32:11.040 回答
0

使用 IN 而不是等于 (=)

SELECT pictures_archive_filename FROM pictures_archive 
WHERE pictures_archive_id IN (SELECT pictures_archive_id 
FROM pictures_archive_category WHERE pictures_category_id = 9)

或者如果可能的话,在 2 个表之间使用 JOIN

于 2012-09-26T08:31:49.697 回答
0
SELECT pictures_archive_filename FROM pictures_archive 
WHERE pictures_archive_id = (SELECT pictures_archive_id 
FROM pictures_archive_category WHERE pictures_category_id = 9 LIMIT 1)
于 2012-09-26T08:33:27.900 回答
0
SELECT p.pictures_archive_filename FROM 
pictures_archive p inner join pictures_archive_category pc 
on p.pictures_archive_id = pc.pictures_archive_id 
where pc.pictures_category_id=9
于 2012-09-26T08:35:49.960 回答