0

I think I have a noob problem in a MySql query with 2 tables.

I'm trying to have the number of comments (comments, Answers) in this case 30, in a MySql query using "inner join" but the consult throws me 244 results.

The names of the tables are comentarios and respuestas, the tables belong to the same service "T.I" in the column: comentario_servicio and respuesta_servicio.

I have 16 answers(respuesta_servicio) and 14 coments(comentario_servicio) so the correct query have to show me 30 results.

Here are my data.

http://sqlfiddle.com/#!2/86b03/1

This is my consult:

select * from respuestas  join comentarios where comentario_servicio = respuesta_servicio
Strawberry
  • 33,750
  • 13
  • 40
  • 57
Paul Noris
  • 103
  • 2
  • 19
  • can you show a sample of your data? possibly in a [sqlFiddle](http://sqlfiddle.com). typically if you are getting more than expected results, it is due to an unexpected cross join. – Sean May 08 '15 at 03:35
  • Thanks man for the attention I really have to see some tutorials to understand what is sqlFiddle and how it works lol, but it was interesting thanks man. The consult now throws me 244. Here is the link : http://sqlfiddle.com/#!2/86b03/1 – Paul Noris May 08 '15 at 05:53
  • based off your data in the sqlFiddle, I think your query should be - `SELECT * FROM respuestas INNER JOIN comentarios ON id_comentario = respuesta_comentario` - http://sqlfiddle.com/#!2/b1510a/2 – Sean May 08 '15 at 13:17
  • Thank you man, your query show me 16 results, and I have 16 answers(respuesta_servicio) and 14 coments(comentario_servicio) so the correct query have to show me 30 results – Paul Noris May 08 '15 at 16:34
  • This seems to return the expected result ?!?!? – Strawberry May 08 '15 at 16:43
  • 1
    I think you want a UNION, not a JOIN – Strawberry May 08 '15 at 16:43
  • Wait, so you just want to return all the rows from both tables, and not join the rows together? So you want a `UNION`? – Sean May 08 '15 at 16:47
  • I don't know man xD, now im trying with union to see what happen but the correct query have to show me 30 results – Paul Noris May 08 '15 at 16:52
  • The issue you will have with `UNION` is that it requires the returned rows from the tables to have the same number of columns. Right now `comentarios` has 5 and `respuestas` has 6. It would be helpful if you could show us what you want the returned rows/data to look like. We are unsure of what your expected results are to be. – Sean May 08 '15 at 17:24

3 Answers3

1

If you're looking for 30 results, which would be a combination of all the records from the two tables, then you likely want to look into using a UNION query.

Using the tables you provided, here is how the query might look. The key to a UNION is having columns with the same name which is why there is a NULL value in the second half.

SELECT
  id_respuestas `id`
  ,respuesta_servicio `servicio`
  ,respuesta_usuario `usuario`
  ,respuesta_respuesta `text`
  ,respuesta_comentario `related_comment`
  ,respuesta_fecha `fecha`
  ,'Respuestas' `type` -- one way to identify the type of record
FROM
  respuestas

union

SELECT
  id_comentario `id`
  ,comentario_servicio `servicio`
  ,comentario_usuario `usuario`
  ,comentario_comentario `text`
  ,NULL `related_comment`
  ,comentario_fecha `fecha`
  ,'Comentario' `type` -- one way to identify the type of record
FROM
  comentarios

A working SQL Fiddle: http://sqlfiddle.com/#!2/86b03/19

How UNION and UNION ALL work: What is the difference between UNION and UNION ALL?

Community
  • 1
  • 1
mattcan
  • 540
  • 12
  • 30
0

Like others said, if you want 30 records as result, you are looking for a UNION, not a JOIN. So try this :

select
  'Comentario' `Table`
  ,id_comentario `id_comentario`
  ,0 `id_respuestas`
  ,comentario_servicio `servicio`
  ,comentario_usuario `usuario`
  ,comentario_comentario `text`
  ,comentario_fecha `fecha`
from comentarios
union
select
  'Respuestas' `Table`
  ,respuesta_comentario `id_comentario`
  ,id_respuestas `id_respuestas`
  ,respuesta_servicio `servicio`
  ,respuesta_usuario `usuario`
  ,respuesta_respuesta `text`
  ,respuesta_fecha `fecha`
from respuestas
order by `id_comentario`,`id_respuestas`

http://sqlfiddle.com/#!2/86b03/23

If you really want a JOIN, you will get only 20 results. First, you don't use the right key to link your tables. Servicio is T.I. everywhere so it's why you get 224 results (16*14=224...not 244 :) ). So, if I understand your structure correctly, the relation is 1 to many...1 Comentario can hav multiple Respuestas. If it's this, you will get 20 results. Second, you need to use an OUTER JOIN. Also, if you ionly want recors for T.I. "servicio", add WHERE comentario_servicio = 'T.I.' after the SELECTstatement. So look at this example :

SQL Fiddle

MySQL 5.5 Schema Setup:

CREATE TABLE `comentarios` (
  `id_comentario` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `comentario_servicio` varchar(45) NOT NULL,
  `comentario_usuario` varchar(45) NOT NULL,
  `comentario_comentario` varchar(500) NOT NULL,
  `comentario_fecha` varchar(45) NOT NULL,
  PRIMARY KEY (`id_comentario`)
);

INSERT INTO `comentarios` (`id_comentario`, `comentario_servicio`, `comentario_usuario`, `comentario_comentario`, `comentario_fecha`) VALUES (46,'T.I','paulnoris','Increible servicio','2015-05-04, 1:50'),(47,'T.I','paulnoris','Al igual que mi compañero estoy muy contento con los resultados que ah tenido la pagina','2015-05-04, 1:59'),(48,'T.I','paulnoris','Asi es estamos contentos con los resultados de la pagina en tan poquito tiempo todo lo que hemos ava','2015-05-04, 2:07'),(49,'T.I','paulnoris','Asi es estamos contentos con los resultados de la pagina en tan poquito tiempo todo lo que hemos ava\r\nquisiera poder escribir muchisimas cosas mas pero pues se entiende que aveces no se puede','2015-05-04, 2:09'),(50,'T.I','paulnoris','veamos cual es el limite de comentarios que puedo hacer si nomas se supone que son 200 letras aver que tanto es porque esta cabron saber cuantas son sin escribirlas todas veamos ya me canse y ya me qu','2015-05-04, 2:10'),(51,'T.I','paulnoris','el alex se la come cruda','2015-05-04, 10:10'),(52,'T.I','paulnoris','se la come el alex','2015-05-04, 13:17'),(53,'T.I','paulnoris','lorem dsad djsaiod jiodjsaoi daojdjroig joid sjoidjs aiodj idjoasisjd osidj aiodj aosijd oiajdos ijdiojigjg fioj giofdjgoifjgoifdj goijaoidj aoisdsaiodjs adiosj diaj dioj iogjfdoigd jgoidfjoisdjdfsdf ','2015-05-06, 11:03'),(54,'T.I','papanoel','Hola amigos tengo una duda sobre si puedo integrarme a otros servicios perteneciendo ya a este','2015-05-06, 12:15'),(55,'T.I','paulnoris','El manchado me la pela','2015-05-06, 13:37'),(56,'T.I','paulnoris','El gilberto se la come cruda','2015-05-06, 16:18'),(57,'T.I','paulnoris','El oswaldo es gay','2015-05-06, 16:19'),(58,'T.I','paulnoris','jasidoja diosajdas','2015-05-06, 18:09'),(59,'T.I','paulnoris','dsadsadsadsada','2015-05-06, 22:08');


CREATE TABLE `respuestas` (
  `id_respuestas` int(11) NOT NULL AUTO_INCREMENT,
  `respuesta_usuario` varchar(45) NOT NULL,
  `respuesta_servicio` varchar(45) NOT NULL,
  `respuesta_respuesta` varchar(500) NOT NULL,
  `respuesta_comentario` int(11) NOT NULL,
  `respuesta_fecha` varchar(45) NOT NULL,
  PRIMARY KEY (`id_respuestas`)
);

INSERT INTO `respuestas` (`id_respuestas`, `respuesta_usuario`, `respuesta_servicio`, `respuesta_respuesta`, `respuesta_comentario`, `respuesta_fecha`) VALUES (8,'paulnoris','T.I','blabla',53,'2015-05-06, 11:43'),(9,'paulnoris','T.I','a',53,'2015-05-06, 11:45'),(10,'paulnoris','T.I','b',53,'2015-05-06, 11:45'),(11,'paulnoris','T.I','c',53,'2015-05-06, 11:45'),(12,'paulnoris','T.I','t',52,'2015-05-06, 11:45'),(13,'paulnoris','T.I','q',52,'2015-05-06, 11:45'),(14,'paulnoris','T.I','y',52,'2015-05-06, 11:45'),(15,'paulnoris','T.I','dsdasda',51,'2015-05-06, 11:51'),(16,'papanoel','T.I','blablabla',53,'2015-05-06, 12:00'),(17,'papanoel','T.I','asi es viejon echale ganas',50,'2015-05-06, 12:00'),(18,'paulnoris','T.I','Desafortunadamente no mi amigo tienes que aba',54,'2015-05-06, 12:16'),(19,'paulnoris','T.I','djsidjo dsaidjoa',55,'2015-05-06, 13:37'),(20,'paulnoris','T.I','Si se la come cruda',56,'2015-05-06, 16:18'),(21,'paulnoris','T.I','Si vale madre es gay',57,'2015-05-06, 16:19'),(22,'paulnoris','T.I','jidsojd iodjs',58,'2015-05-06, 18:10'),(23,'paulnoris','T.I','rgtgrgdgf',59,'2015-05-06, 22:08');

Query 1:

select * from comentarios
left outer join respuestas on id_comentario = respuesta_comentario

Results:

| id_comentario | comentario_servicio | comentario_usuario |                                                                                                                                                                                    comentario_comentario |  comentario_fecha | id_respuestas | respuesta_usuario | respuesta_servicio |                           respuesta_respuesta | respuesta_comentario |   respuesta_fecha |
|---------------|---------------------|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------|---------------|-------------------|--------------------|-----------------------------------------------|----------------------|-------------------|
|            46 |                 T.I |          paulnoris |                                                                                                                                                                                       Increible servicio |  2015-05-04, 1:50 |        (null) |            (null) |             (null) |                                        (null) |               (null) |            (null) |
|            47 |                 T.I |          paulnoris |                                                                                                                 Al igual que mi compañero estoy muy contento con los resultados que ah tenido la pagina |  2015-05-04, 1:59 |        (null) |            (null) |             (null) |                                        (null) |               (null) |            (null) |
|            48 |                 T.I |          paulnoris |                                                                                                     Asi es estamos contentos con los resultados de la pagina en tan poquito tiempo todo lo que hemos ava |  2015-05-04, 2:07 |        (null) |            (null) |             (null) |                                        (null) |               (null) |            (null) |
|            49 |                 T.I |          paulnoris |          Asi es estamos contentos con los resultados de la pagina en tan poquito tiempo todo lo que hemos ava quisiera poder escribir muchisimas cosas mas pero pues se entiende que aveces no se puede |  2015-05-04, 2:09 |        (null) |            (null) |             (null) |                                        (null) |               (null) |            (null) |
|            50 |                 T.I |          paulnoris | veamos cual es el limite de comentarios que puedo hacer si nomas se supone que son 200 letras aver que tanto es porque esta cabron saber cuantas son sin escribirlas todas veamos ya me canse y ya me qu |  2015-05-04, 2:10 |            17 |          papanoel |                T.I |                    asi es viejon echale ganas |                   50 | 2015-05-06, 12:00 |
|            51 |                 T.I |          paulnoris |                                                                                                                                                                                 el alex se la come cruda | 2015-05-04, 10:10 |            15 |         paulnoris |                T.I |                                       dsdasda |                   51 | 2015-05-06, 11:51 |
|            52 |                 T.I |          paulnoris |                                                                                                                                                                                       se la come el alex | 2015-05-04, 13:17 |            12 |         paulnoris |                T.I |                                             t |                   52 | 2015-05-06, 11:45 |
|            52 |                 T.I |          paulnoris |                                                                                                                                                                                       se la come el alex | 2015-05-04, 13:17 |            13 |         paulnoris |                T.I |                                             q |                   52 | 2015-05-06, 11:45 |
|            52 |                 T.I |          paulnoris |                                                                                                                                                                                       se la come el alex | 2015-05-04, 13:17 |            14 |         paulnoris |                T.I |                                             y |                   52 | 2015-05-06, 11:45 |
|            53 |                 T.I |          paulnoris | lorem dsad djsaiod jiodjsaoi daojdjroig joid sjoidjs aiodj idjoasisjd osidj aiodj aosijd oiajdos ijdiojigjg fioj giofdjgoifjgoifdj goijaoidj aoisdsaiodjs adiosj diaj dioj iogjfdoigd jgoidfjoisdjdfsdf  | 2015-05-06, 11:03 |             8 |         paulnoris |                T.I |                                        blabla |                   53 | 2015-05-06, 11:43 |
|            53 |                 T.I |          paulnoris | lorem dsad djsaiod jiodjsaoi daojdjroig joid sjoidjs aiodj idjoasisjd osidj aiodj aosijd oiajdos ijdiojigjg fioj giofdjgoifjgoifdj goijaoidj aoisdsaiodjs adiosj diaj dioj iogjfdoigd jgoidfjoisdjdfsdf  | 2015-05-06, 11:03 |             9 |         paulnoris |                T.I |                                             a |                   53 | 2015-05-06, 11:45 |
|            53 |                 T.I |          paulnoris | lorem dsad djsaiod jiodjsaoi daojdjroig joid sjoidjs aiodj idjoasisjd osidj aiodj aosijd oiajdos ijdiojigjg fioj giofdjgoifjgoifdj goijaoidj aoisdsaiodjs adiosj diaj dioj iogjfdoigd jgoidfjoisdjdfsdf  | 2015-05-06, 11:03 |            10 |         paulnoris |                T.I |                                             b |                   53 | 2015-05-06, 11:45 |
|            53 |                 T.I |          paulnoris | lorem dsad djsaiod jiodjsaoi daojdjroig joid sjoidjs aiodj idjoasisjd osidj aiodj aosijd oiajdos ijdiojigjg fioj giofdjgoifjgoifdj goijaoidj aoisdsaiodjs adiosj diaj dioj iogjfdoigd jgoidfjoisdjdfsdf  | 2015-05-06, 11:03 |            11 |         paulnoris |                T.I |                                             c |                   53 | 2015-05-06, 11:45 |
|            53 |                 T.I |          paulnoris | lorem dsad djsaiod jiodjsaoi daojdjroig joid sjoidjs aiodj idjoasisjd osidj aiodj aosijd oiajdos ijdiojigjg fioj giofdjgoifjgoifdj goijaoidj aoisdsaiodjs adiosj diaj dioj iogjfdoigd jgoidfjoisdjdfsdf  | 2015-05-06, 11:03 |            16 |          papanoel |                T.I |                                     blablabla |                   53 | 2015-05-06, 12:00 |
|            54 |                 T.I |           papanoel |                                                                                                           Hola amigos tengo una duda sobre si puedo integrarme a otros servicios perteneciendo ya a este | 2015-05-06, 12:15 |            18 |         paulnoris |                T.I | Desafortunadamente no mi amigo tienes que aba |                   54 | 2015-05-06, 12:16 |
|            55 |                 T.I |          paulnoris |                                                                                                                                                                                   El manchado me la pela | 2015-05-06, 13:37 |            19 |         paulnoris |                T.I |                              djsidjo dsaidjoa |                   55 | 2015-05-06, 13:37 |
|            56 |                 T.I |          paulnoris |                                                                                                                                                                             El gilberto se la come cruda | 2015-05-06, 16:18 |            20 |         paulnoris |                T.I |                           Si se la come cruda |                   56 | 2015-05-06, 16:18 |
|            57 |                 T.I |          paulnoris |                                                                                                                                                                                        El oswaldo es gay | 2015-05-06, 16:19 |            21 |         paulnoris |                T.I |                          Si vale madre es gay |                   57 | 2015-05-06, 16:19 |
|            58 |                 T.I |          paulnoris |                                                                                                                                                                                       jasidoja diosajdas | 2015-05-06, 18:09 |            22 |         paulnoris |                T.I |                                 jidsojd iodjs |                   58 | 2015-05-06, 18:10 |
|            59 |                 T.I |          paulnoris |                                                                                                                                                                                           dsadsadsadsada | 2015-05-06, 22:08 |            23 |         paulnoris |                T.I |                                     rgtgrgdgf |                   59 | 2015-05-06, 22:08 |
Fabien TheSolution
  • 5,055
  • 1
  • 18
  • 30
-1

Try this

select * from respuestas inner join comentarios on comentario_servicio = respuesta_servicio
Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41