What type of query will accomplish this?
I want a query where searching for 'dave', will display the top three rows. 'mike' and 'carl' both have the parentid of dave. So the three rows displayed will be the top three.
+----+----------+------------+
| id | parentid| user |
+----+----------+------------+
| 1 | null | dave |
| 2 |开发者_运维技巧 1 | mike |
| 3 | 1 | carl |
| 4 | 2 | rick |
| 5 | 4 | mike |
What type of query will accomplish this? A nested query?
No nesting
select
c.*
from
YourTable c
left join YourTable p on p.id = c.parentid
where
p.user = 'dave' /* for the 'children' */ or
c.user = 'dave' /* for Dave himself */
If you don't want Dave himself be returned, but only the children, you can leave 'c.user' from the where
clause. In this case you can also change left join
to inner join
which is merginally faster, although you may not notice it in this query.
Select * from
table_name as partA inner join table_name as partB on partA.id = partB.parentid
Where partA.user = "Dave" or partB.user = "Dave"
精彩评论