mysql - 限制左连接

时间:2016-06-03 12:58:00

标签: mysql sql

左说,例如我有以下查询,并希望限制表上的left join,我该如何实现?

SELECT * FROM Base
LEFT JOIN Derived1 ON Base.id = Derived1.id
LEFT JOIN Derived2 ON Base.id = Derived2.id
LEFT JOIN Derived3 ON (Base.id = Derived3.id WHERE Derived3.name LIKE 'test%' LIMIT 5) <-----
WHERE Base.id = 'someid';

我虽然可以这样写:

SELECT * FROM Base
LEFT JOIN Derived1 ON Base.id = Derived1.id
LEFT JOIN Derived2 ON Base.id = Derived2.id
LEFT JOIN Derived3 ON Base.id = (
    SELECT d3.id FROM Derived3 d3
    WHERE d3.name LIKE 'test%' AND Base.id = Derived3.id
    LIMIT 5
)
WHERE Base.id = 'someid';

但是这给了我不正确的结果

我想要Derived3内的所有数据,但如果Derived.name等于test 1test 2test 3等,则只需要5个项目。 表格中可能有1亿次测试,还有其他几千种不以'test'开头的测试。

所以基本上,给我Derived3内的任何内容以及以'test'开头的最多5行。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

检查下面的查询。

SELECT *
FROM Base
LEFT JOIN Derived1 ON Base.id = Derived1.id
LEFT JOIN Derived2 ON Base.id = Derived2.id
LEFT JOIN Derived3 ON (
        Base.id = Derived3.id
        AND Derived3.id IN (
            SELECT Derived3.id
            FROM Derived3
            WHERE Derived3.NAME LIKE 'test%' LIMIT 5
            )
        )
WHERE Base.id = 'someid'

答案 1 :(得分:0)

我不确定这是否适合您的方案,但您可以使用过滤器LIKE 'test%'从Derived3中进行选择,并使用别名加入选择结果。

我没有安装MySql来试试这个,但是这样的东西应该可以工作:

SELECT * FROM Base
LEFT JOIN Derived1 ON Base.id = Derived1.id
LEFT JOIN Derived2 ON Base.id = Derived2.id
LEFT JOIN (
    SELECT d3.id FROM Derived3 d3
    WHERE d3.name LIKE 'test%'
    LIMIT 5
) Derived3Alias ON Base.id = Derived3Alias.id
WHERE Base.id = 'someid'
GROUP BY Base.id;

也许你需要写“作为Derived3Alias”,但首先尝试没有'as',我认为它应该有效。