Basically I have these 2 simple mysql tables:
CREATE TABLE `users` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) NOT NULL,
`relation` int(10) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `mytable` (
`id` int(10) UNSIGNED NOT NULL,
`user` int(10) UNSIGNED NOT NULL,
`data` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`tier` tinyint(3) UNSIGNED NOT NULL,
`parent_id` int(10) UNSIGNED DEFAULT NULL COMMENT 'same table'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `users` (`id`, `name`, `relation`) VALUES
(12, 'user1', 5),
(20, 'user2', NULL),
(21, 'user3', NULL);
INSERT INTO `mytable` (`id`, `user`, `data`, `tier`, `parent_id`) VALUES
(1, 12, 'test1', 1, NULL),
(2, 20, 'test2', 2, 1),
(3, 21, 'test3', 3, 1),
(4, 20, 'test4', 1, NULL);
I need to select all rows from 'mytable' that are related with the users.relation = 5
To do that I use the following query:
SELECT mytable.*
FROM mytable
LEFT JOIN users ON mytable.user = users.id
WHERE users.relation = 5
The problem is that I also need to select the rows from mytable
that have a parent_id connected with the above results.
WHERE mytable.id = X OR mytable.parent_id = X
Basically in this example, the expected output should be all rows of mytable except the last one (because is not connected with users.relation = 5)
You need another join of mytable
to your query:
SELECT m.*
FROM mytable m INNER JOIN (
SELECT m.*
FROM mytable m
INNER JOIN users u ON m.user = u.id
WHERE u.relation = 5
) t ON t.id IN (m.id, m.parent_id)
I changed the join to INNER
join, because although you use LEFT
join the WHERE
clause changes it to INNER
since it filters out any unmatched rows.
See the demo .
Results:
> id | user | data | tier | parent_id
> -: | ---: | :---- | ---: | --------:
> 1 | 12 | test1 | 1 | null
> 2 | 20 | test2 | 2 | 1
> 3 | 21 | test3 | 3 | 1
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.