0

I have two tables, one of the holds tools, the other one holds the tools history like location and who has it. I need to run a search question on this tables and have tried this

SELECT tblmaskin.* 
FROM `tblmaskin` 
INNER JOIN tblmaskinhistorik ON tblmaskin.maskinId=tblmaskinhistorik.maskinId 
WHERE tblmaskin.maskin='".$_POST['sok']."' 
OR tblmaskinhistorik.var='".$_POST['sok']."'
 OR  tblmaskinhistorik.anvandarnamn='".$_POST['sok']."'

But the problem is that I only want to search the last inserted row for that tool in the history table. When you do a search for a tool by place for example you only want to get the tool that is there now.

Is there a way to do that?

SQL Fiddle example.

Vyktor
  • 20,559
  • 6
  • 64
  • 96

2 Answers2

1

A side note: It looks you're using PHP and you're not using prepared statement, check out PDO or mysqli to avoid SQL injection.

There's actually an article in official MySQL docs about this + similar thing was already solved here and here.

You need to run a sub-query to fetch id of the "latest" history record (assuming record with max id is the right one) and then use that id to fetch correct record.

Note: I've replaced your inlined php variables with PDO's named placeholders

SELECT tblmaskin.* 
FROM `tblmaskin` 
-- Select record from tblmaskinhistorik with the highest id
INNER JOIN (SELECT maskinId, MAX(maskinhistId) AS maxid
           FROM tblmaskinhistorik
           GROUP BY maskinId) AS t_max
    ON t_max.maskinId = tblmaskin.maskinId
-- Joining whole row
INNER JOIN tblmaskinhistorik ON t_max.maxid=tblmaskinhistorik.maskinhistId
WHERE tblmaskin.maskin=:sok 
    OR tblmaskinhistorik.var=:sok
    OR tblmaskinhistorik.anvandarnamn=:sok

Run EXPLAIN on the query to ensure that it's working efficiently.

Community
  • 1
  • 1
Vyktor
  • 20,559
  • 6
  • 64
  • 96
  • Not working, if i do a search on a user tblmaskinhistorik.anvandarnamn i don't get all the tools that user have right now and i also get other users tools. Thanx for trying i might just cheat and add two fields in the tool table that contains the last user and place. But it really irritates me I hate giving up. – user2978137 Oct 20 '14 at 11:11
  • @user2978137 it should be `INNER JOIN tblmaskinhistorik ON t_max.maxid=tblmaskinhistorik.maskinhistId` (wrong id checked), try it out; I'm adding sqlfiddle example to your question. Also please add expected results. – Vyktor Oct 20 '14 at 11:40
-1

insert limit 1 order by 'your field' desc with your query

Jobayer
  • 1,221
  • 1
  • 14
  • 22