How do I select a value whose id don't exist as parent to others, in mysql?
Two questions:
- My table has three fields:
id,parent_id,name. Initiallyidis0, for an element that is a child to the current element, theparent_idis set to theidof the current ele开发者_Python百科ment....basically, infinite nesting concept. Now I need to find those elements which do not have any children or sub-elements. Any ideas? - What is the best choice to retrieve the
id(auto_increment) of a record I just inserted? mysql_insert_id or last_insert_id, or something else? I need to insert two records simultaneously and use the id(primary key) from the first record as foreign key of second record.
- use SELF JOIN
SELECT f.is,f.parent_id,f.name FROM table f LEFT JOIN table s ON s.id = f.parent_id WHERE s.parent_id = 0
- use
last_insert_id
1) Not sure I understand your schema and how parent_id works...
SELECT
t1.id
FROM
table t1
LEFT OUTER JOIN
table t2
ON
t1.id = t2.parent_id
WHERE
t2.parent_id IS NULL
2) LAST_INSERT_ID() is the function which returns the last autoincrement generated on the connection. I don't know what mysql_insert_id was referring to... mysql_last_insert_id in PHP perhaps? That's a PHP function that wraps a call to LAST_INSERT_ID().
I solved it by using:
SELECT * FROM `nestmenu` WHERE `id` NOT IN (SELECT `parent_id` AS `id` FROM `nestmenu`)
However, as you can tell, this query is not at all optimized, but it does get the job done. Any ideas how to optimize it?
加载中,请稍侯......
精彩评论