mysql 限制第一个表上的左连接

wvyml7n5  于 2022-12-10  发布在  Mysql
关注(0)|答案(4)|浏览(146)

我有两个表:宝石和宝石细节是左连接。我正在尝试将左联接限制为GEMS表中的10条记录。还有另外两个加入的表(GemReplay和USERS),但它们不会导致问题。以下操作不起作用:

SELECT
    gems.gemid,
    gems.title,
    r.tot,
    gemdetail.filename
FROM
    (
        (
            gems
        LEFT JOIN(
            SELECT
                gemid,
                COUNT(*) AS tot
            FROM
                gemreply
            GROUP BY
                gemid
        ) AS r
    ON
        gems.gemid = r.gemid
        )
    LEFT JOIN gemdetail ON gems.gemid = gemdetail.gemid
    )
LEFT JOIN users ON gems.userid = users.userid
WHERE
    gems.grade = '7'
ORDER BY
    gems.gemid
LIMIT 0, 10;

这将返回的总行数限制为10,但是由于每个gem都有多个详细记录,所以我只剩下不到10个gem记录。我看过每一篇“极限”的帖子,但没有发现这种情况。
此版本的MySQL尚不支持‘Limit&IN/All/Any/Some子查询’。

nbnkbykc

nbnkbykc1#

诸如此类的事

SELECT * FROM A
      INNER JOIN ( SELECT * FROM A WHERE A.FIELD1='X' ORDER BY A.FIELD2 LIMIT 10) X
             ON (A.KEYFIELD=X.KEYFIELD)
      LEFT JOIN B ON (A.FIELD = B.FIELD)
      LEFT JOIN C ON (A.FIELD = C.FIELD)
bz4sfanl

bz4sfanl2#

试试这个:

SELECT g.gemid, g.title, r.tot, gemdetail.filename
FROM (SELECT * FROM gems WHERE grade = '7' LIMIT 10) g
LEFT JOIN (SELECT gemid, COUNT(*) AS tot FROM gemreply GROUP BY gemid) r
          ON r.gemid = g.gemid
LEFT JOIN gemdetail ON g.gemid = gemdetail.gemid
LEFT JOIN users ON g.userid = users.userid
ORDER BY g.gemid;

这应该行得通。

jk9hmnmh

jk9hmnmh3#

WITH LAST_ORDERS AS(SELECT*FROM ORDERS WHERE ID IN(SELECT MAX(ID)FOR ORDERS GROUP BY CUSTOMER_ID))SELECT Customers.id,stomers.first_name,Customers.last_name,last_orders.order_date,last_orders.Order_Status from Customers Join Last_Orders on Customers.id=last_orders.Customer_id Order by Customer_id;

ukdjmx9f

ukdjmx9f4#

十年后,我可以在一对多JOIN的左侧表上的嵌套查询中LIMIT记录,其中左侧表将返回多条记录--即使连接的右侧表上的字段上有WHEREORDER BY子句。

  • 在内部查询中,具有满足WHERE子句所需的具有联接的所有表。在那里应用限制。
  • 在外部查询中,重新连接到所有相同的表以添加多对多字段
SELECT
    alias.field_from_A,
    alias.field_from_B
FROM (
    SELECT DISTINCT
     /* ONLY fields from LEFT table (or tables
        with a one to one relationship with it) will
        allow LIMIT to apply only to the LEFT table. DISTINCT is needed due to JOIN*/
      A.field_from_A
    FROM
      A
      /* JOIN to your hearts content on tables
         which need to satisfy WHERE and ORDER BY */
      LEFT JOIN B ON A.field_from_A = B.field_from_B
      WHERE A.field_from_A = 'value' AND B.field_from_B = 'value 2'
      ORDER BY A.field_from_A, B.field_from_B
      LIMIT 0, 10
    ) alias
/* JOIN the one to many tables here to add the field info */
LEFT JOIN B ON A.field_from_A = B.field_from_B
/* the WHERE and ORDER BY need to be applied again */
WHERE alias.field_from_A = 'value' AND B.field_from_B = 'value 2'
ORDER BY alias.field_from_A, B.field_from_B

相关问题