2016-07-18 10 views
1

Ich habe eine Tabelle mit JSON-Daten in ihm, und eine Aussage, die für jede Zeile eine Reihe von IDs zieht ...mySQL WHERE IN von JSON Array

SELECT items.data->"$.matrix[*].id" as ids 
FROM items 

Diese in etwas Ergebnisse wie ..

+------------+ 
| ids  | 
+------------+ 
| [1,2,3] | 
+------------+ 

Weiter mag ich aus einer anderen Tabelle auszuwählen, in dem die ID der anderen Tabelle in der Anordnung ist, ähnlich wie die WHERE id IN ('1,2,3') jedoch unter Verwendung des JSON-Array ...

Etwas nach dem Vorbild von ...

SELECT * FROM other_items 
WHERE id IN ( 
    SELECT items.data->"$.matrix[*].id" FROM items 
); 

aber es einige JSON Magie braucht, und ich kann es nicht funktionieren ...

+0

Ist das '[1,2,3]', wie in dieser entsprechenden Spalte gespeicherten Daten? Ich meine Komma-getrennte 'ids', die von '[' '' '' ''? – 1000111

+0

[dieser Beitrag] (http://stackoverflow.com/questions/32188341/how-to-query-with-a-where-clause-in-mysql-json-table) ist relevant –

+0

die resultierenden Daten sind ein mySQL JSON ARRAY –

Antwort

1

Unten finden Sie eine vollständige Antwort. Möglicherweise möchten Sie eine 'use <db_name>;'-Anweisung am Anfang des Skripts. Der Punkt ist zu zeigen, dass JSON_CONTAINS() verwendet werden kann, um den gewünschten Join zu erreichen.

DROP TABLE IF EXISTS `tmp_items`; 
DROP TABLE IF EXISTS `tmp_other_items`; 

CREATE TABLE `tmp_items` (`id` int NOT NULL PRIMARY KEY AUTO_INCREMENT, `data` json NOT NULL); 
CREATE TABLE `tmp_other_items` (`id` int NOT NULL, `text` nvarchar(30) NOT NULL); 

INSERT INTO `tmp_items` (`data`) 
VALUES 
    ('{ "matrix": [ { "id": 11 }, { "id": 12 }, { "id": 13 } ] }') 
, ('{ "matrix": [ { "id": 21 }, { "id": 22 }, { "id": 23 }, { "id": 24 } ] }') 
, ('{ "matrix": [ { "id": 31 }, { "id": 32 }, { "id": 33 }, { "id": 34 }, { "id": 35 } ] }') 
; 

INSERT INTO `tmp_other_items` (`id`, `text`) 
VALUES 
    (11, 'text for 11') 
, (12, 'text for 12') 
, (13, 'text for 13') 
, (14, 'text for 14 - never retrieved') 
, (21, 'text for 21') 
, (22, 'text for 22') 
-- etc... 
; 

-- Show join working: 
SELECT 
    t1.`id` AS json_table_id 
, t2.`id` AS joined_table_id 
, t2.`text` AS joined_table_text 
FROM 
    (SELECT st1.id, st1.data->'$.matrix[*].id' as ids FROM `tmp_items` st1) t1 
INNER JOIN `tmp_other_items` t2 ON JSON_CONTAINS(t1.ids, CAST(t2.`id` as json), '$') 

Sie sollten die folgenden Ergebnisse sehen:

Results

+0

Gutes Beispiel! Das Mitnehmen ist die 'JSON_CONTAINS()' Funktion: https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html –