左加入分页(LIMIT)

时间:2017-01-08 16:04:18

标签: php mysql doctrine-orm symfony

想象一下,我有一个这样的表,有多对一的关系

表1

  id | name
   1 | as
   2 | df
   3 | gh

  id | othercontents | table1relationship
   1 | qw            | 1
   2 | er            | 2
   3 | ty            | 3
   4 | ui            | 3

如果我在Table1上使用表2的左连接运行select查询但是将其限制为3个结果我将返回3行

1 - as - qw
2 - df - er
3 - gh - ty

然而我想要

1 - as - qw
2 - df - er
3 - gh - [ty,ui]

现在,我现在正常选择它,然后自己将其他内容放入数组中,将我的行转换为我想要的行,但问题仍然是我无法返回我想要的所有行。

逻辑上,我想我想限制为X unique table1.id而不是仅限于X行,但如果可能的话,我不知道如何实现这种逻辑。

当然,如果我选择数据库中的所有内容然后在PHP中对其进行排序,这很容易,但这太过密集了,我不想选择20,000行来获得~10行。我想一个讨厌的方法是选择30行,然后自己进行排序并按照我的要求返回10,但是对我来说选择超过我需要的东西似乎仍然很愚蠢。

或许值得一提,但我正在使用Symfony3 w / Doctrine并使用查询构建器。但我并不是要求复制/粘贴我的问题的答案,而只是推动这个方向,以便我可以继续实施。

由于

1 个答案:

答案 0 :(得分:1)

这是一个会给你结果的查询(如果我理解你是正确的)。

SELECT t1.id,t1.name,
    CONCAT( IF(sum(1)>1,'[',''), GROUP_CONCAT(t2.othercontents), IF(sum(1)>1,']','')) AS name2
FROM (
    SELECT *
    FROM table1 
    LIMIT 3
    ) as t1
LEFT JOIN table2 t2 on t2.table1relationship = t1.id
GROUP BY t2.table1relationship;

<强>样品

mysql> SELECT * from table1;
+----+------+
| id | name |
+----+------+
|  1 | as   |
|  2 | df   |
|  3 | gh   |
+----+------+
3 rows in set (0,00 sec)

mysql> SELECT * from table2;
+----+---------------+--------------------+
| id | othercontents | table1relationship |
+----+---------------+--------------------+
|  1 | qw            |                  1 |
|  2 | er            |                  2 |
|  3 | ty            |                  3 |
|  4 | ui            |                  3 |
+----+---------------+--------------------+
4 rows in set (0,00 sec)

<强>结果

mysql> SELECT t1.id,t1.name,
    ->     CONCAT( IF(sum(1)>1,'[',''), GROUP_CONCAT(t2.othercontents), IF(sum(1)>1,']','')) AS name2
    -> FROM (
    ->     SELECT *
    ->     FROM table1
    ->     LIMIT 3
    ->     ) as t1
    -> LEFT JOIN table2 t2 on t2.table1relationship = t1.id
    -> GROUP BY t2.table1relationship;
+----+------+---------+
| id | name | name2   |
+----+------+---------+
|  1 | as   | qw      |
|  2 | df   | er      |
|  3 | gh   | [ui,ty] |
+----+------+---------+
3 rows in set (0,00 sec)

mysql>
相关问题