0

Two questions:

  1. My table has three fields: id, parent_id, name. Initially id is 0, for an element that is a child to the current element, the parent_id is set to the id of the current element....basically, infinite nesting concept. Now I need to find those elements which do not have any children or sub-elements. Any ideas?
  2. 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.
Ocaso Protal
  • 19,362
  • 8
  • 76
  • 83
Bluemagica
  • 5,000
  • 12
  • 47
  • 73

3 Answers3

0

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().

Dan Grossman
  • 51,866
  • 10
  • 112
  • 101
0
  1. 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
  1. use last_insert_id
xkeshav
  • 53,360
  • 44
  • 177
  • 245
-1

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?

Bluemagica
  • 5,000
  • 12
  • 47
  • 73