对于未应用于子行的父级的JOIN ... LIMIT,LIMIT记录

时间:2015-09-23 11:54:26

标签: php mysql database

我已将分页应用于我的数据。我通过复杂的连接查询获取我的数据,没有任何子查询只有简单的连接。

假设这个查询[这是一个非常简单的查询,我有查询,这是复杂的]

SELECT 
   states.states_name , 
   countries.countrty_name , 
   states.state_id , 
   countries.country_id 
FROM  countries 
INNER JOIN   states ON     countries.country_id =  states.country_id
WHERE  countries.status = "1"  AND  states.status = "1" 

这里可能会有不同国家的机会。 意味着美国可以有30个州,印度可以有26个州,巴基斯坦可以有15个州......

我想要什么 现在我想以一种方式查询,如果我想第一次获得前5个国家的数据...再次为另外5个国家意味着限制5,10 ....之后另外5个国家。

如果你有我的问题,那么任何想法.... ??如何实现......?或者无法通过MySQL实现?

表示仅限制父母......不限制孩子...

实施例

Countries    No of states
  USA            30
  INDIA          25
  UK             10
  FRANCE         18  
  CHINA          48     // so for the first time it will return this much rows [SUM OF THIS 5 COUNTRIES row]  ...  but only top 5 country 


  JAPAN          11
  UKRAINE        05
  RUSSIA         70
  GERMANY        10 
  SPAIN          06   // so for the second time it will return this much rows [SUM OF THIS 5 COUNTRIES row]  ...  but only seconmd top 5 country 


  ARGENTINA      03
  BRAZIL         23
  NORTH KOREA    14
  SOUTH KOREA    12  // so for the second time it will return this much rows [SUM OF THIS 5 COUNTRIES row]  ...  but only last top 5[available all if not 5] country 




 select    *
                         FROM saved_card sc
                         inner join redeem_code redeem On redeem.redeem_id = sc.redeem_id And redeem.status = '1'
                         inner join cards card On card.card_id = redeem.card_id And card.status = '1' And card.expiry_date >= '".$today."'
                         left join card_additional_info cinfo on cinfo.card_id = card.card_id And cinfo.status = '1'
                         where sc.user_id = '".$userId."'
                           And sc.status = '1'
                           And card.what_to_broadcast = '".$type."'
                           And redeem.used_coupon = '1'
                         ORDER BY redeem.redeem_id DESC, card.card_id ,cinfo.card_additional_info_id

这里有一张卡片有多个saved_cards,它将是每个用户和每个redeem_coupon。 并且一张卡将有多个附加信息。

我想通过saved_card获取数据...意味着应该限制5张已保存的卡片,另外5张和另外5张卡片......

在每个saved_card [它将有一对一连接到redeem_code]并且只连接到一张卡[因为卡是父卡]但可以有多个card_additional_info文件[因为父母是卡,它可以有多个孩子。]

1 个答案:

答案 0 :(得分:1)

您可以尝试使用子查询:

SELECT 
    states.states_name, 
    countries.countrty_name, 
    states.state_id, 
    countries.country_id 
FROM
    countries 
INNER JOIN
    states ON countries.country_id =  states.country_id
WHERE
    countries.status = "1"
    AND states.status = "1"
    AND countries.country_id IN (
        SELECT country_id FROM countries LIMIT 5, 5)

显然,LIMIT的值必须用您的分页逻辑替换。

或者如果你想要它,就像你提供的例子一样:

SELECT 
    c.countrty_name, 
    COUNT(s.state_id) AS "states" 
FROM
    countries AS c
LEFT JOIN
    states AS s ON c.country_id =  s.country_id
WHERE
    c.status = "1"
    AND s.status = "1"
GROUP BY
    c.country_id
LIMIT
    5, 5

应该这样做。