获取带有限制的数据库连接表

时间:2017-06-01 04:01:54

标签: mysql sql database join

我一直试图加入两个表,但只显示来自联接表的有限数量(2)的结果。不幸的是我没能得到正确的结果。这些是我的表格:

目的地

id   name
------------
1    Bahamas
2    Caribbean
3    Barbados

航程

id  name            destination
---------------------------------
1   Adventure       1  
2   For Kids        2
3   All Inclusive   3
4   Seniors         1
5   Singles         2
6   Disney          1
7   Adults          2

这是我试过的查询:

SELECT 
   d.name as Destination,
   s.name as Sailing 
FROM destinations d
JOIN sailings s 
  ON s.destination = d.id
LIMIT 2

但由于限制,这给了我2个:

Destination    Sailing
-------------------------
Bahamas        Adventure
Caribbean      For Kids

示例: SQL FIDDLE

我希望LIMIT 2仅应用于已加入的表sailings

预期结果:

Destination    Sailing
-------------------------
Bahamas        Adventure
Bahamas        Seniors
Caribbean      Singles
Caribbean      For Kids

有人可以指出我正确的方向吗?

3 个答案:

答案 0 :(得分:2)

尝试

select tmp.name as destination,d.name as sailings  from (
SELECT
    id,
    name,
    destination
FROM
(
    SELECT
        id,
        name,
        destination,
        @rn := IF(@p = destination, @rn + 1, 1) AS rn,
        @p := destination
    FROM sailings
    JOIN (SELECT @p := NULL, @rn := 0) AS vars
    ORDER BY destination 
) AS T1
WHERE rn <= 2
  )tmp
 JOIN (SELECT * FROM destinations limit 0,2) d 
  ON(tmp.destination=d.id)

我制作了2个派生表并加入了它们

答案 1 :(得分:2)

您的问题是,您希望为表中的每个组获取组中两个最高(或最低)的成员。在这种情况下,您希望每个目的地组的前两次航行。

在支持分析函数的数据库中处理此查询的规范方法是使用ROW_NUMBER()。但由于MySQL不支持这一点,我们可以使用会话变量来模拟它:

SET @row_number = 0;
SET @destination = NULL;

SELECT
    t.Destination,
    t.Sailing
FROM
(
    SELECT
        @row_number:=CASE WHEN @destination = Destination
                          THEN @row_number + 1 ELSE 1 END AS rn,
        @destination:=Destination AS Destination,
        Sailing,
        id
    FROM
    (
        SELECT s.id AS id, d.name AS Destination, s.name AS Sailing
        FROM destinations d
        INNER JOIN sailings s
            ON s.destination = d.id
    ) t
    ORDER BY
        Destination,
        id
) t
WHERE t.rn <= 2
ORDER BY
    t.Destination,
    t.rn;

请注意,巴巴多斯显示为单行,因为在您的示例数据中,它只有一个航行。如果您还想限制只有两次或多次航行的目的地,也可以这样做。

<强>输出:

enter image description here

在这里演示:

Rextester

答案 2 :(得分:0)

你能试试吗

SELECT 
   d.name as Destination,
   s.name as Sailing 
FROM sailings s
JOIN (SELECT * from destinations LIMIT 2) d  
  ON s.destination = d.id

(你说你想限制sailings表,但我认为你可能希望根据你的预期输出对destinations表进行限制;你可以根据需要进行调整)