MySQL Inner Join With LIMIT to left table

試著忘記壹切 提交于 2019-12-08 18:53:14

问题


I have this database query

SELECT *
FROM (`metadata` im)
INNER JOIN `content` ic ON `im`.`rev_id`  = `ic`.`rev_id`
WHERE `im`.`id` = '00039'
AND `current_revision` = 1
ORDER BY `timestamp` DESC
LIMIT 5, 5 

The query limits the total rows in the result to 5. I want to limit the left table metadata to 5 without limiting the entire result-set.

How should I write the query?


回答1:


If you think about what you are trying to do, you're not really doing a select against metadata.

You need to sub query that first.

Try:

SELECT *
FROM ((select * from metadata limit 5) im)
INNER JOIN `content` ic ON `im`.`rev_id`  = `ic`.`rev_id`
WHERE `im`.`id` = '00039'
AND `current_revision` = 1
ORDER BY `timestamp` DESC



回答2:


Well, I think you mean LEFT JOIN try using LEFT JOIN instead of INNER JOIN

    SELECT DISTINCT *
    FROM (`metadata` im)
    INNER JOIN `content` ic ON `im`.`rev_id`  = `ic`.`rev_id`
    WHERE `im`.`id` = '00039'
    AND `current_revision` = 1
    ORDER BY `timestamp` DESC
    LIMIT 5, 5 



回答3:


Here is another possible approach:

SET @serial=0;
SET @thisid=0;

SELECT 
   @serial := IF((@thisid != im.id), @serial + 1, @serial), 
   @thisid := im.id,
   * 
FROM (`metadata` im)
WHERE `im`.`id` = '00039'
AND `current_revision` = 1
AND @serial < 5
ORDER BY `timestamp` DESC

This isn't tested. Please let me know if you run into issue implementing this - and I can elaborate.



来源:https://stackoverflow.com/questions/5126653/mysql-inner-join-with-limit-to-left-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!