gpt4 book ai didi

mysql - 避免返回多行

转载 作者:行者123 更新时间:2023-11-29 07:30:37 25 4
gpt4 key购买 nike

我有三个表:reserva、cliente、estancia

reserva
___________
id
id_cliente
entrada
salida
...

cliente
__________
id
nombre
apellidos
telefono
dni
....

estancia
__________
id
id_cliente
id_reserva

其中 cliente 和 reserva 具有 1 对 1 的关系。目前我使用这个查询。

SELECT r.id as rid,
r.entrada as rentrada,
r.salida as rsalida,
c.nombre as cnombre,
c.telefono as ctelefono,
c.dni as cdni,
c.apellidos as capellido
FROM reserva r INNER JOIN
cliente c
ON r.id_mainclient = c.id
ORDER BY rid DESC

我还需要添加 estancia,它与 reserva 是 n 对 1 的关系。我需要的可能是使用 group_concat() 这样我仍然可以在 estancia 中获取所有 id_clientes 而无需复制行,而是将它们连接起来。

最佳答案

您可以使用 group by 来使用 group_concat

  SELECT r.id as rid
, r.entrada as rentrada
, r.salida as rsalida
, c.nombre as cnombre
, c.telefono as ctelefono
, c.dni as cdni
, c.apellidos as capellido
, group_concat(e.id_cliente)
FROM reserva r
INNER JOIN cliente c on r.id_mainclient = c.id
INNER JOIN estancia e on r.id = e.id_reserva
GROUP BY r.id
ORDER BY rid DESC

或使用适当的分隔符并按

排序
SELECT r.id as rid
, r.entrada as rentrada
, r.salida as rsalida
, c.nombre as cnombre
, c.telefono as ctelefono
, c.dni as cdni
, c.apellidos as capellido
, group_concat(e.id_cliente ORDER BY e.id_cliente ASC SEPARATOR ' ')
FROM reserva r
INNER JOIN cliente c on r.id_mainclient = c.id
INNER JOIN estancia e on r.id = e.id_reserva
GROUP BY r.id
ORDER BY rid DESC

或者如果你还需要 c.dni

  SELECT r.id as rid
, r.entrada as rentrada
, r.salida as rsalida
, c.nombre as cnombre
, c.telefono as ctelefono
, c.dni as cdni
, c.apellidos as capellido
, group_concat(e.id_cliente ORDER BY e.id_cliente ASC SEPARATOR ' ')
, group_concat(c.dni SEPARATOR ' ')
FROM reserva r
INNER JOIN cliente c on r.id_mainclient = c.id
INNER JOIN estancia e on r.id = e.id_reserva
GROUP BY r.id
ORDER BY rid DESC

关于mysql - 避免返回多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51443763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com