我有2张桌子
work_assets ----------------------------------------------------- id | asseturl | previmgurl | carid ----------------------------------------------------- 1 | "pic1.jpg" | "pic2.jpg" | 1 2 | "pic3.jpg" | "pic4.jpg" | 1 3 | "pic5.jpg" | "pic6.jpg" | 2 . | ... | ... | . . | ... | ... | . cases ----------------------------------------------------- id | ... | carid | ... ----------------------------------------------------- 1 | ... | 1 | ... 2 | ... | 2 | ... 3 | ... | 69 | ... . | ... | ... | ... . | ... | ... | ...
我希望我可以执行某种类型的查询Q,使我可以进入JSON,而该JSON实际上是cases具有从carid列到关联的asseturl和的一对多关系的表previmgurl,例如
Q
cases
carid
asseturl
previmgurl
[ { id : 1, ..., assetinfo: [ { asseturl : "pic1.jpg", previmgurl: "pic2.jpg"}, { asseturl : "pic3.jpg", previmgurl: "pic4.jpg"} ], ... }, { id : 2, ... }, { id: 3, ... }, . . . ]
设置:
var cases = <?php $Q = ????; echo json_encode($wpdb->get_results($Q)); ?>
这可能吗?
恕我直言,您真的不需要在mysql端进行json转换,因为它效率不是很高,几乎没有意义。
但是只是为了证明这是可能的(与@bannmatt意见相反),这是我的方法:
http://sqlfiddle.com/#!9/6bffb/7
SELECT c.*, CONCAT('assetinfo : [ ', COALESCE( GROUP_CONCAT( CONCAT("{ asseturl: ", wa.asseturl, ', previmgurl: ', wa.previmgurl," }") ), ''), ' ]') FROM cases c LEFT JOIN work_assets wa ON c.carid = wa.carid GROUP BY c.id