基于列的值限制(不是行数)

时间:2013-04-29 16:20:14

标签: mysql sql join

我想限制以下查询产生的短语数量:

SELECT phrase_txt, word_txt FROM phrase_word
LEFT JOIN phrase ON phrase.id = phrase_word.phrase_id
LEFT JOIN word ON word.id = phrase_word.word_id;

| PHRASE_TXT | WORD_TXT |
-------------------------
|     Iambad |        i |
|     Iambad |       am |
|     Iambad |      bad |
|        Car |      car |
|     tellme |     tell |
|     tellme |       me |

预期产出:

| PHRASE_TXT | WORD_TXT |
-------------------------
|     Iambad |        i |
|     Iambad |       am |
|     Iambad |      bad |
|        Car |      car |

添加 LIMIT 0,2 没有帮助,因为它限制了单词的数量,而不是短语。让我们说2:

| PHRASE_TXT | WORD_TXT |
-------------------------
|     Iambad |        i |
|     Iambad |       am |

SQL Fiddle中的详细信息。

3 个答案:

答案 0 :(得分:2)

您可以将LIMIT放在子查询中以限制返回的phrases的数量:

SELECT phrase_txt, 
  word_txt 
FROM 
(
  select phrase_txt, id
  from phrase
  order by id
  limit 2
) p
LEFT JOIN phrase_word
  ON p.id = phrase_word.phrase_id
LEFT JOIN word 
  ON word.id = phrase_word.word_id

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

尝试:

SELECT phrase.text AS p, word.text AS w FROM phrase_word
  JOIN (select * from phrase limit 2) phrase ON phrase.id = phrase_word.phrase_id
  LEFT JOIN word ON word.id = phrase_word.word_id;

SQLFiddle here

答案 2 :(得分:0)

我不确定你为什么使用Left Join? 嗯,这是我能想到的最简单的:

 SELECT phrase.text AS p, 
        word.text AS w 
   FROM phrase_word
  INNER JOIN phrase 
     ON phrase.id = phrase_word.phrase_id
  INNER JOIN word 
     ON word.id = phrase_word.word_id
  INNER JOIN 
        (
            SELECT distinct id 
              FROM phrase 
             Limit 2 ) T1
     ON phrase.id = T1.id;