![](/img/trans.png)
[英]How to get a one-to-many result when the MySQL query is based on a second relationship in the related table?
[英]How can I return all relationship data in one mysql query and stop only one result being concatanated when querying by relationship
我正在嘗試執行 MYSQL 查詢,該查詢檢索關系數據並將其連接到 json 對象的串聯字符串中,我稍后會對其進行 json_decode。
我在這里設置了一個小提琴,但 JSON_OBJECT 不起作用。 架構在 markdown 表中或下方。
我想要達到的最終結果是下表中的結果。
ID | 標題 | 發布日期 | 藝術家 | 流派 |
---|---|---|---|---|
1 | 我的歌 | 2022-01-01 15:00:01 | [{id: 1, name: 'Pauli', is_featuring: 0}, {id: 2, name: 'Tony', is_featuring: 1}] | [{id:1,名稱:'Rock'},{id:2,名稱:'Pop'}] |
下面是使用藝術家 ID 根據藝術家檢索歌曲的查詢。 我得到了一個歌曲列表,但如果歌曲中有多個藝術家,它只返回其 id 傳遞給 sql 查詢的藝術家。
當嘗試按流派查詢時會發生類似的事情。
所以我的問題是如何在結果中返回我想要的數據,同時對藝術家或流派進行查詢? 我還必須計算查詢將返回的結果總數的總記錄數。
SELECT ms.id, ms.title, ms.date_published,
CONCAT('[', GROUP_CONCAT(DISTINCT(JSON_OBJECT('id', ma.id, 'name', ma.name, 'is_featuring', mas.is_featuring_artist)) ORDER BY mas.id separator ','), ']') AS artists,
CONCAT('[', IF(mg.id IS NULL, '', GROUP_CONCAT(DISTINCT(JSON_OBJECT('id', mg.id, 'name', mg.name)) ORDER BY mg.name separator ',')), ']') AS genres
FROM songs ms
LEFT JOIN artist_song mas ON mas.song_id = ms.id
LEFT JOIN artists ma ON ma.id = mas.artist_id
LEFT JOIN genre_song mgs ON mgs.song_id = ms.id
LEFT JOIN genres mg ON mg.id = mgs.genre_id
WHERE ma.id = 2 AND ms.published = 1
GROUP BY ms.id
ORDER BY ms.date_published DESC
LIMIT 10
OFFSET 0;
這是我要回來的結果。 請注意,當我查詢 id 為 2 的藝術家時,藝術家 Pauli 不再在藝術家數組中。
ID | 標題 | 發布日期 | 藝術家 | 流派 |
---|---|---|---|---|
1 | 我的歌 | 2022-01-01 15:00:01 | [{id: 2, name: 'Tony', is_featuring: 1}] | [{id:1,名稱:'Rock'},{id:2,名稱:'Pop'}] |
下面是表格
歌曲表
ID | 姓名 | 發表 |
---|
藝術家表
ID | 姓名 |
---|
藝術家歌曲表
ID | 藝術家 ID | 歌曲編號 | is_featured |
---|
流派表
ID | 姓名 |
---|
流派歌曲表
ID | 流派_id | 歌曲編號 |
---|
你需要加入artist_song
兩次。 其中一個限制選擇的歌曲,另一個是讓所有藝術家都上這首歌。
SELECT ms.id, ms.title, ms.date_published,
CONCAT('[', GROUP_CONCAT(DISTINCT(JSON_OBJECT('id', ma.id, 'name', ma.name, 'is_featuring', mas.is_featuring_artist)) ORDER BY mas.id separator ','), ']') AS artists,
CONCAT('[', IF(mg.id IS NULL, '', GROUP_CONCAT(DISTINCT(JSON_OBJECT('id', mg.id, 'name', mg.name)) ORDER BY mg.name separator ',')), ']') AS genres
FROM songs ms
JOIN artist_song mas1 ON mas1.song_id = ms.id
JOIN artist_song mas ON mas.song_id = ms.id
JOIN artists ma ON ma.id = mas.artist_id
LEFT JOIN genre_song mgs ON mgs.song_id = ms.id
LEFT JOIN genres mg ON mg.id = mgs.genre_id
WHERE mas1.artist_id = 2 AND ms.published = 1
GROUP BY ms.id
ORDER BY ms.date_published DESC
LIMIT 10
OFFSET 0;
無需兩次加入artists
,因為在限制時您沒有使用該表中的任何內容。 您可以從mas1.artist_id
限制藝術家 ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.