簡體   English   中英

MySQL子查詢多個結果

[英]Mysql subquery multiple results

查詢

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
    )

)

如何artist_id僅返回artist_id 一次,並在單獨的數組中返回圖像ID? 我也嘗試INNER JOIN images ON images.artist_id = :artist_id ,但返回的內容類似。

嘗試在您的php端執行此操作。 這會容易得多

免責聲明:我可能寫過兩次php。所以我絕對不是php專家。但這就是我會嘗試做的。 如果有錯誤,任何人都可以糾正該代碼;)

設置:我創建了一個數組數組,就像您擁有數組一樣。 制作了一個名為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);

一種選擇是運行兩個單獨的查詢:

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 set運算符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 Artists表table, and which are from the 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM