避免返回多行

a0zr77ik  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(204)

我有三张table:reserva,cliente,estancia

reserva
___________
id
id_cliente
entrada
salida
...

cliente
__________
id
nombre
apellidos
telefono
dni
....

estancia
__________
id
id_cliente
id_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 . 我需要的也许是 group_concat() 所以我还是可以得到所有的 id_clientesestancia 不复制行,而是连接行。

lp0sw83n

lp0sw83n1#

您可以使用group\ U concat using group by

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

相关问题