我有一张有两把钥匙的桌子,我不能把桌子分成两张。
第一个键,id是一个计数器。第二个键是parent_id。
例如:
id,parent_id,text
1,你好史蒂夫 - 这是比尔
2,1,嗨 - 比尔怎么样?
3,0,早上好Janice
4,3,你好 - 早上好,
第一条记录是对话的父记录,第二条记录是子记录。
我遇到的困难是写一个查询,当你传递任何一个id时,它会返回单个对话的记录。
例如:
select * from table where id = 2 or parent_id = ( select parent_id from table where id = 2 )
select * from table where id = 1 or parent_id = ( select parent_id from table where id = 1 )
第一个查询将起作用,返回id为1和2的记录。第二个不会因为它将返回id为3的行,因为如果你传递1,那么parent_id将为零。
我确信这很简单,因为分析瘫痪而遗失了。
感谢。
答案 0 :(得分:2)
将AND parent_ID <> 0
添加到子查询中。
答案 1 :(得分:2)
此查询将检索:
SELECT DISTINCT * FROM
(
--is a child of the specified parent
SELECT * from table WHERE parent_id = @SomeID
UNION ALL
-- is the record specified by ID
SELECT * from table WHERE ID = @SomeID
--and get the parent itself
OR ID = (SELECT parent_id FROM table WHERE ID = @SomeID)
UNION ALL
--all siblings with the same parent
SELECT * FROM table WHERE parent_id = (SELECT parent_id
FROM table WHERE ID = @SomeID)
AND parent_id>0
) F
ORDER BY ID
答案 2 :(得分:1)
-- I *think* from OP's description , this should do it.
-- The first SELECT will _always_ bring back a single row (the ID is unique and known to the issuer of the query).
-- The second SELECT may bring back zero, one or many rows
-- So (if my understanding is correct) in English:
-- Bring back the row for the given ID and all (if any) rows which have me as a parent_id.
-- Rehashed : joining up the IDs from parent->child
-- Again, not tried...
SELECT * FROM table parent WHERE parent.id = <id>
union
SELECT * FROM table child WHERE child.id=parent.id;