Mysql子查询多个结果

时间:2014-07-02 18:41:57

标签: php mysql arrays

查询

SELECT artists.artist_id, images.img_id 
FROM `artists`, `images` 
WHERE artists.artist_id = :artist_id 
AND images.artist_id = :artist_id

返回以下内容,例如:

Array
(
[0] => Array
    (
        [artist_id] => 80
        [img_id] => 4
    )

[1] => Array
    (
        [artist_id] => 80
        [img_id] => 5
    )

[2] => Array
    (
        [artist_id] => 80
        [img_id] => 6
    )

[3] => Array
    (
        [artist_id] => 80
        [img_id] => 140
    )

)

如何制作它以便仅返回<{1}} 一次并将图像ID返回到单独的数组中? 我也尝试了artist_id,但返回了类似的东西。

2 个答案:

答案 0 :(得分:0)

尝试在php端执行此操作。它会容易得多

免责声明:我已经写了两次php ...所以我绝不是php的专家..但这是我会尝试做的。如果错误,任何人都可以随意更正代码;)

SETUP:我创建了一个数组数组,就像你拥有它一样。 做了一个名为image_ids的空数组 将img_id推送到该数组上以获得img_id的

数组
$test = Array
(
 Array
    (
        artist_id => 80,
        img_id => 4
    ),

Array
    (
        artist_id => 80,
        img_id => 5
    ),

Array
    (
        artist_id => 80,
        img_id => 6
    ),

Array
    (
        artist_id => 80,
        img_id => 140
    )

);

设置后 - 编码时间!:

$image_ids = Array();
$artist = 0;
foreach ($test as $my_array){ // $test is the variable the whole array is equal to
    array_push($image_ids, $my_array['img_id']);
}
$artist = $my_array['artist_id']; // my_artist is the last element in the array currently

echo 'the artist is: ', $artist;
echo 'the images he made are :';
print_r ($image_ids);

答案 1 :(得分:0)

一种选择是运行两个单独的查询:

SELECT artists.artist_id
  FROM `artists`
 WHERE artists.artist_id = :artist_id 

SELECT images.img_id
  FROM `images`
 WHERE images.artist_id = :artist_id

如果这两列的数据类型是等价的(即两者都是整数),我们可以合并两个查询(使用UNION ALL集合运算符to return a single list of id values. We could add a discriminator column to the result set, to identify which rows are from the艺术家table, and which are from the images`表。

例如:

SELECT 'artist_id'         AS src
     , artists.artist_id   AS id
  FROM `artists`
 WHERE artists.artist_id = :artist_id 
 UNION ALL
SELECT 'img_id'            AS src
  FROM images.img_id
  FROM `images`
 WHERE images.artist_id = :artist_id