Home > Back-end >  Get the last record with INNER JOIN
Get the last record with INNER JOIN

Time:11-16

I'm trying to get the last record, but I ger the first record. What am I doing wrong?

My Table permission

|id|pid|uid|
| 1| 2 | 2 |
| 2| 5 | 2 |

My Table fruits

|id|pid|number1|number2|
|1 | 1 | 50    | 100   |
|2 | 1 | 10    | 100   |
|3 | 1 | 100   | 100   |    <== Try get last record

I want get the last record, but I can't.

I create the query, but not work:

SELECT DISTINCT(fruits.pid), permission.pid, fruits.number1, fruits.number2 
FROM permission 
LEFT JOIN fruits ON permission.pid = fruits.pid 
WHERE permission.uid = '2' 
GROUP BY fruits.pid 
ORDER BY fruits.id DESC

I need the result:

|pid|pid|number1|number2|
|3  | 1 | 100   | 100   |

CodePudding user response:

Your join doesn't join any rows. The value of fruits.pid is always 1. The values of permissions.pid are (2, 5). Thus, your join of fruits.pid = permission.pid doesn't find any rows that match, so you're not getting the results you expect. If you drop the DISTINCT in the query and remove the GROUP BY (which causes it to fail in MySQL 8) your query produces:

pid     pid number1 number2
null    2   null    null
null    5   null    null

The row you want isn't in the result set, so of course you don't get it.

The other problem you have is that the number 3 is not in the column fruits.pid. It's an id value, so I suspect you're joining on the wrong field. And you've got permission.pid as the second field returned by your query, but that column only contains 2 and 5, as noted earlier, but you want a value of 1 there; thus, it appears you want to return fruits.pid as the second column of the result set. So something like:

SELECT fruits.id, fruits.pid, fruits.number1, fruits.number2 
FROM fruits 
LEFT JOIN permission
  ON permission.id = fruits.pid 
WHERE permission.uid = '2' 
ORDER BY fruits.id DESC

db<>fiddle here

  • Related