Anda perlu menggunakan FIND_IN_SET()
berfungsi sebagai kriteria join:
SELECT info.*, GROUP_CONCAT(targets.value) AS value
FROM info LEFT JOIN targets ON FIND_IN_SET(targets.id, info.target_ids)
GROUP BY info.id
Lihat di sqlfiddle .
Namun, Anda mungkin sebaiknya menormalkan struktur data Anda dan simpan relasi info-target Anda dalam tabel terpisah:
CREATE TABLE InfoTargets (
InfoID INT NOT NULL,
TargetID INT NOT NULL,
PRIMARY KEY (InfoID, TargetID),
FOREIGN KEY (InfoID) REFERENCES info (id),
FOREIGN KEY (TargetID) REFERENCES targets (id)
);
INSERT INTO InfoTargets VALUES
(1,2),
(3,4), (3,1),
(4,2), (4,3), (4,1);
ALTER TABLE Info DROP COLUMN target_ids;
Maka Anda akan melakukan:
SELECT info.id,
GROUP_CONCAT(targets.id) AS target_ids,
GROUP_CONCAT(targets.value) AS value
FROM InfoTargets
LEFT JOIN info ON InfoID = InfoTargets.InfoID
LEFT JOIN targets ON TargetID = InfoTargets.TargetID
GROUP BY info.id
Jika urutan target penting (dan mungkin berbeda antara setiap info
item), Anda perlu membuat rank
tambahan kolom di InfoTargets
.