1

例如,我有 3 个表:

表 1(id,值) 表 2(id,fk,值) 表 3(id,fk,值)

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 收集在一个地方。我怎样才能做到这一点?

4

1 回答 1

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

于 2013-08-11T13:54:37.610 回答