1

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

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中的更多详细信息。

4

3 回答 3

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

于 2013-04-29T17:14:57.327 回答
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在这里

于 2013-04-29T17:13:47.227 回答
0

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

 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;
于 2013-04-29T17:19:09.920 回答