且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用单个查询从多个表中提取

更新时间:2023-01-23 10:42:13

您应该能够通过自联接实现此目的,例如:

You should be able to achieve this with a self-join, like :

SELECT DISTINCT e2.eventId
FROM event_tags e1
INNER JOIN event_tags e2 
    ON e2.tagName LIKE CONCAT('%', e1.tagName, '%') AND e2.eventId != e1.eventId
WHERE e1.eventId = {}

我注意到第二个查询有一个 LIMIT 3 子句.首先,请注意,如果没有 ORDER BY 子句,这不会产生可预测的结果.这是一个基于窗口函数 ROW_NUMBER()(在 MySQL 8 中可用)的解决方案,它为每个匹配的标签生成不超过 3 个 event_id :

I notice that the second query has a LIMIT 3 clause. First of all, please note that without an ORDER BY clause this does not produces predictable results. Here is a solution based on window function ROW_NUMBER() (available in MySQL 8), that will produce not more than 3 event_id for each matching tag :

SELECT DISTINCT event_id FROM (
    SELECT e2.eventId, ROW_NUMBER() OVER(PARTITION BY e1.eventId ORDER BY e2.eventId) rn
    FROM event_tags e1
    INNER JOIN event_tags e2 
        ON e2.tagName LIKE CONCAT('%', e1.tagName, '%') AND e2.eventId != e1.eventId
    WHERE e1.eventId = {}
) WHERE rn <= 3