MySQL子查询使用相同的id字段两次从一个表中进行描述

时间:2011-03-31 01:57:16

标签: php mysql mysql-error-1242

SELECT move.idItem, item.description, ( SELECT location.location_name as movedFrom FROM move, location WHERE move.idlocationFrom = location.idlocation ) AS movedFrom, ( SELECT location.location_name as movedTo FROM move, location WHERE move.idlocationTo = location.idlocation ) AS movedTo FROM move , item WHERE move.idItem = item.idItem

我正在尝试使用上面的查询获取locationTo和movedFrom的名称,这会在PHPMyAdmin中生成'#1242 - Subquery返回多行'错误。

描述 项目移动存储在名为“移动”的表中。项目可以从一个位置移动到另一个位置,存储位置ID(存储在“位置”表中的位置名称)和存储在“项目”表中的项目名称。 movedTo和movedFrom将存储位置表中的id。

有人可以帮我解决这个问题吗? 提前致谢

2 个答案:

答案 0 :(得分:1)

我认为您可能希望使用联接而不是子查询。类似的东西:

SELECT move.idItem, 
       item.description, 
       location1.location_name movedFrom, 
       location2.location_name as movedTo
FROM move 
INNER JOIN location location1 ON move.idlocationFrom = locatio1n.idlocation
INNER JOIN location location2 ON move.idlocationTo = location2.idlocation
INNER JOIN item ON move.idItem = item.idItem

答案 1 :(得分:0)

Table 1 -  cpe Table

|id | name
|----------
| 1 | cat
| 2 | dog
| 3 | mouse
| 4 | snake
-----------

Table 2 - AutoSelect

|id  | name   |  cpe1_id |  cpe2_id  | cpe3_id |
|-----------------------------------------------
| 1  | user1  |  1       |  3        | 4       |
| 2  | user2  |  3       |  1        | 2       |
| 3  | user3  |  3       |  3        | 2       |
| 4  | user4  |  4       |  2        | 1       |
------------------------------------------------

I would like to see an output of

user1 | cat   | mouse  |  snake  |
user2 | mouse | snake  |  dog    | 
..etc

 SELECT a.name, cpe1.name, cpe2.name, cpe3.name FROM AutoSelect as a
 LEFT JOIN cpe as cpe1 ON ( cpe1.id = a.cpe1_id ) 
 LEFT JOIN cpe as cpe2 ON ( cpe2.id = a.cpe2_id ) 
 LEFT JOIN cpe as cpe3 ON ( cpe3.id = a.cpe3_id )