避免多个内部联接以从同一个表中添加新列(info)

时间:2016-11-27 20:08:54

标签: mysql sql select join

我想知道是否有办法从this fiddle的架构中为nameuser_idsender_user_id提供recipient_user_id个信息。

我现在能想到的唯一方法就是做这个嵌套的内连接,我觉得效率很低:

SELECT e.id
    ,msg_owner
    ,msg_owner_name
    ,sender_user_id
    ,sender_name
    ,recipient_user_id
    ,f.NAME AS recipient_name
    ,msg_body
    ,created_at
FROM (
    SELECT c.id
        ,msg_owner
        ,msg_owner_name
        ,sender_user_id
        ,d.NAME AS sender_name
        ,recipient_user_id
        ,msg_body
        ,created_at
    FROM (
        SELECT a.id
            ,user_id AS msg_owner
            ,NAME AS msg_owner_name
            ,sender_user_id
            ,recipient_user_id
            ,msg_body
            ,created_at
        FROM messages AS a
        INNER JOIN users AS b ON a.user_id = b.id
        ) AS c
    INNER JOIN users AS d ON c.sender_user_id = d.id
    ) AS e
INNER JOIN users AS f ON e.recipient_user_id = f.id

是否有任何(更有效的)方法为上述三列中的每一列引入name值?感谢您的回答/建议!

2 个答案:

答案 0 :(得分:1)

您可以在同一查询中拥有多个(most recent call last)<ipython-input-193-7227d35394c0> in <module>() 1 for node in links: #loops through each link and changes each dictionary to a tuple so networkx can read in the information 2 edges = node.items() ----> 3 G.add_edge(*edges[0]) #takes the tuple from the list and unpacks the tuples 4 5 nx.draw(G) TypeError: 'dict_items' object does not support indexing 子句,而无需嵌套。我不确定,如果这会提高性能,但至少它会使查询不那么麻烦:

join

答案 1 :(得分:1)

只使用连接,而不是嵌套连接。

按照您的方式,您强制数据库收集每个内部查询的所有结果,然后将其连接到另一个表。除非通过WHERE子句对最内层查询的内容非常有限,否则这对性能总是不利。

以下是使用连接的正确方法。它允许直接使用索引(如果存在)来加快速度。

dns-01