Skip to content

Instantly share code, notes, and snippets.

@faytranevozter
Last active October 19, 2022 14:52
Show Gist options
  • Save faytranevozter/59c858345a401e383d778a91b324edc0 to your computer and use it in GitHub Desktop.
Save faytranevozter/59c858345a401e383d778a91b324edc0 to your computer and use it in GitHub Desktop.
sub query tabel yang sama
-- create schema
CREATE TABLE users (
id int not null primary key auto_increment,
name varchar(50) not null,
parent_id int null default null
);
-- insert data
INSERT INTO users (id, name, parent_id) VALUES
(1, 'Zaki', 2),
(2, 'Ilham', NULL),
(3, 'Irwan', 2),
(4, 'Arka', 3);
-- query
SELECT
u.id,
u.name,
(
SELECT su.name FROM users su WHERE id = u.parent_id
) AS parent_name
FROM users u
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment