例如,我有3个表:
table1(id,value)table2(id,fk,value)table3(id,fk,value)
table2和table3是table1的子项。
我有以下SQL查询:
query = "SELECT" +
" t1.id AS _id," +
" t2.id AS t2_id," +
" t2.fk as t2_fk," +
" t2.value as t2_value," +
" t3.id AS t3_id," +
" t3.fk as t3_fk," +
" t3.value as t3_value," +
" FROM t1 table1" +
" INNER JOIN table2 t2 ON t1.id = t2.fk" +
" INNER JOIN table3 t3 ON t1.id = t3.fk" +
" WHERE t2.value like '%"+lookingFor+"%' LIMIT 10";
光标给出以下结果:
如何做到这一点:
我的目的是避免重复值,同时在一个地方收集所有t3_value。我怎么能实现这个目标?
答案 0 :(得分:2)
试试这个:
query = "SELECT" +
" t1.id AS _id," +
" t2.id AS t2_id," +
" t2.fk as t2_fk," +
" t2.value as t2_value," +
" GROUP_CONCAT(t3.value) as t3_value," +
" FROM t1 table1" +
" INNER JOIN table2 t2 ON t1.id = t2.fk" +
" INNER JOIN table3 t3 ON t1.id = t3.fk" +
" WHERE t2.value like '%"+lookingFor+"%'
GROUP BY t1.id, t2.id, t2.fk, t2.value LIMIT 10 ";
并了解您想要的是“GROUP_CONCAT(X,Y)” - 部分参考here。