开发者

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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜