Virajsinh

tbl_family_relationships.sql

Jul 16th, 2025 (edited)
344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 1.72 KB | Source Code | 0 0
  1. -- A and B are children of C
  2. INSERT INTO family_relationships (child_id, parent_id, relation_type) VALUES
  3. (1, 3, 'father'),
  4. (2, 3, 'father');
  5.  
  6. -- C is a child of D
  7. INSERT INTO family_relationships (child_id, parent_id, relation_type) VALUES
  8. (3, 4, 'father');
  9.  
  10. INSERT INTO `family_relationships` (`id`, `child_id`, `parent_id`, `relation_type`, `created_at`) VALUES
  11. (NULL, '1', '5', 'mother', current_timestamp()),
  12. (NULL, '2', '5', 'mother', current_timestamp());
  13.  
  14. -- Select Query
  15.  
  16. WITH RECURSIVE descendants AS (
  17.   SELECT
  18.     fr.parent_id,
  19.     fr.child_id,
  20.     1 AS level
  21.   FROM family_relationships fr
  22.   WHERE fr.parent_id = 4
  23.  
  24.   UNION ALL
  25.  
  26.   SELECT
  27.     fr.parent_id,
  28.     fr.child_id,
  29.     d.level + 1
  30.   FROM family_relationships fr
  31.   JOIN descendants d ON fr.parent_id = d.child_id
  32. )
  33. SELECT
  34.   d.level,
  35.   r.id,
  36.   CONCAT(r.first_name, ' ', r.middle_name, ' ', r.last_name) AS full_name
  37. FROM descendants d
  38. JOIN tbl_registration r ON r.id = d.child_id
  39. ORDER BY d.level;
  40.  
  41. -- Select Query Father With Mother
  42.  
  43. SELECT
  44.     c.id AS child_id,
  45.     CONCAT(c.first_name, ' ', c.middle_name, ' ', c.last_name) AS child_name,
  46.  
  47.     -- Father
  48.     CONCAT(f.first_name, ' ', f.middle_name, ' ', f.last_name) AS father_name,
  49.  
  50.     -- Mother
  51.     CONCAT(m.first_name, ' ', m.middle_name, ' ', m.last_name) AS mother_name
  52.  
  53. FROM tbl_registration c
  54.  
  55. -- Father Join
  56. LEFT JOIN family_relationships fr_f ON fr_f.child_id = c.id AND fr_f.relation_type = 'father'
  57. LEFT JOIN tbl_registration f ON fr_f.parent_id = f.id
  58.  
  59. -- Mother Join
  60. LEFT JOIN family_relationships fr_m ON fr_m.child_id = c.id AND fr_m.relation_type = 'mother'
  61. LEFT JOIN tbl_registration m ON fr_m.parent_id = m.id
  62.  
  63. WHERE c.id IN (1,2)
  64.  
  65. ORDER BY c.id;
  66.  
Tags: mysql Database
Advertisement
Add Comment
Please, Sign In to add comment