简体   繁体   English

Mysql 左连接与双同表关系 where 子句

[英]Mysql left join with double same-table relation where clause

Basically I have these 2 simple mysql tables:基本上我有这两个简单的 mysql 表:

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我需要 select 'mytable' 中与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.问题是我还需要 select mytable中具有与上述结果相关的parent_id的行。

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)基本上在这个例子中,预期的 output 应该是 mytable 除了最后一行之外的所有行(因为没有连接 users.relation = 5)

You need another join of mytable to your query:您需要另一个mytable连接到您的查询:

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.我将联接更改为INNER联接,因为尽管您使用LEFT ,但WHERE子句将其更改为INNER ,因为它会过滤掉任何不匹配的行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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