MYSQL加入两个表(+限制基于第一个table)

MYSQL JOIN TWO TABLES (+ LIMIT based on first table)

我有 2 个这样的 table:-

Table: offers  
|-------------- |
| id | OfferNum |
| 1  | a1       |
| 2  | a2       |
| 3  | a3       |
| 4  | a4       |
| 5  | a5       |
| 6  | a6       |
|---------------|

Table: colours 
|------------------------------------------|
| id | OfferNum  | colour    | availaility |
| 1  | a1        |blue       |yes          |
| 2  | a1        |red        |no           |
| 3  | a2        |green      |yes          |
| 4  | a3        |white      |yes          |
| 5  | a3        |brown      |yes          |
| 6  | a3        |navy       |no           |
| 7  | a3        |black      |yes          |
| 8  | a3        |red        |yes          |
| 9  | a4        |yellow     |no           |
| 10 | a5        |black      |yes          |
| 11 | a6        |white      |yes          |
|------------------------------------------|

出于分页目的,我需要 select 来自 table "offers" 的 3 个 OfferNums,从偏移量 0 开始,并加入两个 table 以便生成结果行将包含 3 个 offernums(即 a1、a2 和 a3)。等等..

以下脚本,LIMIT 0,3 没有产生预期的结果。

SELECT offers.OfferNum, items.colour, items.availability
FROM offers
    JOIN items ON items.OfferNum = offers.OfferNum
ORDER BY offers.id ASC 
LIMIT 0 , 3

它仅生成连接的 table 的前 3 行。像这样:-

|----------------------------|
|OfferNum|colour|availability|
|a1      |blue  |yes         |
|a1      |red   |no          |
|a2      |green |yes         |
|----------------------------|

有没有办法达到预期的效果?

将 LIMIT 子句移动到子查询中并与之连接:

SELECT offers2.OfferNum, items.colour, items.availability
FROM (SELECT * FROM offers ORDER BY id LIMIT 0, 3) AS offers2
JOIN items ON items.OfferNum = offers2.OfferNum
ORDER BY ...

如果我没理解错的话,您想显示报价 table 中的 3 个报价并同时显示第二个 table 中的所有等效值,那么您可以考虑 select 数据你想要作为基础的,比如:

SELECT OfferNum
    FROM offers
ORDER BY id ASC 
    LIMIT 0 , 3

然后从它 select 加入你需要的 JOIN 类型 查询看起来像:

SELECT customOffers.OfferNum, items.colour, items.availability
FROM 
(SELECT OfferNum
    FROM offers
ORDER BY id ASC 
    LIMIT 0 , 3) as customOffers
    JOIN items ON items.OfferNum = offers.OfferNum

问题出在 MYSQL 4.0.

低于Mysql 4.1 的版本不支持子查询 subselect sql query doesn't work on mysql 4

此处有更多详细信息:http://dev.mysql.com/doc/refman/4.1/en/subqueries.html

为了快速修复,我安装了 MYSQL 4.1,Irakli Gigiberia 和 Salman A 的回复都有效。

非常感谢您的帮助。