简体   繁体   中英

Select data from two related columns in MySql

table proyectos has two related columns, id_pro and id_padre

    CREATE TABLE IF NOT EXISTS `proyectos` (
  `id_pro` int(8) unsigned NOT NULL,
  `ot_padre` int(8) unsigned NOT NULL,
  `nom_pro` varchar(255) NOT NULL,
  PRIMARY KEY (`id_pro`)
) DEFAULT CHARSET=utf8;
INSERT INTO `proyectos` (`id_pro`, `ot_padre`, `nom_pro`) VALUES
  ('1', '0', 'Proyecto 1'),
  ('2', '0', 'Proyecto 2'),
  ('3', '0', 'Proyecto 3'),
  ('4', '3', 'Proyecto hijo 1'),
  ('5', '3', 'Proyecto hijo 2');

CREATE TABLE IF NOT EXISTS `servicios` (
  `id_ser` int(8) unsigned NOT NULL,
  `id_pro` int(8) unsigned NOT NULL,
  `nom_ser` varchar(255) NOT NULL,
  PRIMARY KEY (`id_ser`)
) DEFAULT CHARSET=utf8;
INSERT INTO `servicios` (`id_ser`, `id_pro`, `nom_ser`) VALUES
  ('1', '1', 'Servicio a'),
  ('2', '1', 'Servicio b'),
  ('3', '3', 'Servicio c'),
  ('4', '3', 'Servicio d'),
  ('5', '4', 'Servicio e'),
  ('6', '5', 'Servicio e');

How can obtain all data from servicios with id_pro 3, and also all service with id_padre 3?

EDIT**

expected output

id_ser |  id_pro |   nom_ser   |
3      |  3      |  Servicio c |
4      |  3      |  Servicio d |
5      |  4      |  Servicio e |
6      |  5      |  Servicio f |

schema and query http://sqlfiddle.com/#!9/a1e0dc/1/0

You need an INNER join of the tables:

SELECT s.* 
FROM servicios s INNER JOIN proyectos p
ON p.id_pro = s.id_pro 
WHERE 3 IN (p.id_pro, p.ot_padre)

See the demo .
Results:

id_ser id_pro nom_ser
3 3 Servicio c
4 3 Servicio d
5 4 Servicio e
6 5 Servicio f
SELECT DISTINCT * FROM Servicios 
WHERE id_pro = 3
OR id_pro IN 
    (SELECT id_pro 
    FROM Proyectos 
    WHERE id_padre = 3)

Outputs:

id_ser  id_pro  nom_ser
3   3   Servicio c
4   3   Servicio d
5   4   Servicio e

It seems to me that you're actually after this:

SELECT *
  FROM servicios
 WHERE id_pro = 3
 UNION
SELECT s.*
  FROM servicios s
  JOIN proyectos p
    ON p.id_pro = s.id_pro
 WHERE p.ot_padre = 3;

(There are various ways of writing this, including a LEFT JOIN with COALESCE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM