简体   繁体   中英

MySQL WHERE ORDER BY on INSERT

I looked through the documentation and I didn't seem to find anything describing how to do what I'm attempting. Then again, I didn't find anything saying you couldn't either.

$querytotal = "insert into offer_det where where fname = '".$fname."' and lname = '".$lname."' ORDER BY id DESC LIMIT 1 (`t1`, `t2`, `t3`, `t4`)
values($t1, $t2, $t3, $t4)";
$resultotal = mysql_query($querytotal);

My question: Is this an appropriate INSERT statement to make? Essentially I'm just needing to match the first and last name, and then pick the most recent table entry for them, since there could be multiple table entries with the same first and last name. From there all I need to do is insert the four values t1-4 with my variables $t1-4.

I saw this link but it didn't make a whole lot of sense.

Thanks for bearing with me on this one.

I think you want something like this...

$querytotal = "insert into offer_det (t1, t2, t3, t4) " .
"select t1, t2, t3, t4 from offer_det where fname = '$fname' and lname = '$lname' order by id desc limit 1";
$resultotal = mysql_query($querytotal);

Your sql is incorrect. Try this.

RE-RE EDITED:

$querytotal = "insert into offer_det (`t1`, `t2`, `t3`, `t4`) values(’$t1’, ’$t2’, ’$t3’, ’$t4’) where  id = (SELECT max(id) FROM offer_det where fname = '".$fname."' and lname = '".$lname."')"; 
$resultotal = mysql_query($querytotal); 

But are you sure you need an insert and not an update query?

Im not sure what you want but, maybe you need something like this

    $query = "Insert into offer_det (t1, t2, t3, t4)
               (SELECT $t1, $t2, $t3, $t4 FROM offer_det where
              fname = '".$fname."' and lname = '".$lname."' ORDER BY ID DESC Limit 1)";

This will insert (t1, t2, t3, t4) in this table, based on last result with fname and lnam from same table.

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