简体   繁体   中英

How can I select a row plus all its related rows?

Here is my table structure:

// mytable
+----+---------+
| id | related |
+----+---------+
| 1  | NULL    |
| 2  | 1       |
+----+---------+

Now I need to select the row that has id = 1 and all rows that have related = 1 . Here is my query:

select m1.*
from mytable m1
left join mytable m2 on m1.id = m2.related
where m1.id = 1

But it returns just the first row. What's wrong?

You can do:

select t.*
from mytable t
where 1 in (id, related);

No self-join is needed.

EDIT:

If you want performance, then write the query as:

select t.*
from mytable t
where id = 1
union all
select t.*
from mytable t
where related = 1;

And define two indexes on mytable(id) and mytable(related) .

If I understood correctly you are looking for this:

select m1.*
from mytable m1 where m1.id = 1 or m1.related = 1

You need to use inner join.

select m1.*
from mytable m1
inner join mytable m2 on m1.id = m2.related
where m1.id = 1

You can try UNION ALL or if you don't want duplicates use UNION

select * from mytable m1 where m1.id = 1
UNION
select * from mytable m2 where m2.related = 1

Can you try this code

SELECT * FROM table WHERE (id = 1 AND related IS NULL) OR related = 1;

I create a table with more items and it returns what you want. Check this 在此处输入图片说明

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