简体   繁体   中英

Trying to select all the records from table B that have the same name as most recently added record from table A

I'm using php and MySQL. I have two tables. I want to select all the records from table PARTS that have the same prod_name as the most recently added record in the table PRODUCTS .

Table PRODUCTS :

  • id (auto increment)
  • prod_name

Table PARTS :

  • prod_name
  • part_name
  • part_cost

Will this work or should I use some sort of join?

SELECT * FROM parts WHERE prod_name = (SELECT prod_name FROM products ORDER BY id DESC LIMIT 1)

Yes it will work. You can always execute the query in the phpmyadmin or MySql Query Browser to test it.

It may be better to return the inserted id, and select using that id.

SELECT
  parts.*
FROM
  parts
INNER JOIN
  products
ON
  products.prod_name = parts.prod_name
WHERE
  products.id = (SELECT MAX(id) FROM products)

That should work - but if products has an auto increment id, why are you using the prod_name as the foreign key in the PARTS table?

Such a design buys you extra work if the user ever wants to change the prod_name (you then have to go through and change the prod_name on all the PARTS, unless you don't mind them losing their connection).

Plus it is not space efficient (unless prod_name is always very short).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM