Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Try this</p> <pre><code>SELECT DISTINCT @pv := usr.userid, CONCAT( "[", CONVERT( GROUP_CONCAT(DISTINCT "{\"id\":", usr.userid, ", \"subjects\":", ( SELECT CONCAT( "[", CONVERT( GROUP_CONCAT( "{\"id\":", subjectid, ", \"subjectname\":\"", subjectname, "\"}" ) USING utf8 ) , "]" ) FROM subjectdetails WHERE subjectid IN ( SELECT subjectid FROM UserDetails WHERE userid = @pv) ), ", \"username\":\"", usr.username, "\"}" ) USING utf8 ) , "]" ) AS jsn FROM User usr JOIN UserDetails det ON det.userid = usr.userid LEFT OUTER JOIN subjectdetails sub ON sub.subjectid = det.subjectid </code></pre> <p>Output:</p> <pre><code>ID JSN 1 [{"id":1, "subjects":[{"id":1, "subjectname":"basic science"},{"id":2, "subjectname":"advance mathematics"},{"id":4, "subjectname":"geography"}], "username":"robert"},{"id":2, "subjects":[{"id":1, "subjectname":"basic science"},{"id":2, "subjectname":"advance mathematics"},{"id":4, "subjectname":"geography"}], "username":"albert"}] </code></pre> <p>The JSN column having the structure </p> <pre><code>[ { "id": 1, "subjects": [ { "id": 1, "subjectname": "basic science" }, { "id": 2, "subjectname": "advance mathematics" }, { "id": 4, "subjectname": "geography" } ], "username": "robert" }, { "id": 2, "subjects": [ { "id": 1, "subjectname": "basic science" }, { "id": 2, "subjectname": "advance mathematics" }, { "id": 4, "subjectname": "geography" } ], "username": "albert" } ] </code></pre> <p><a href="http://sqlfiddle.com/#!2/635e4/2" rel="nofollow">SQLFIDDLE</a></p> <p>Note: The JSON structure in your question is not a valid one. Use <a href="http://pro.jsonlint.com/" rel="nofollow">jsonlint</a> to generate valid json.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload