在PHP中结合多个MySQL表的更好方法?

时间:2018-10-26 18:16:49

标签: php mysql database left-join

我正在开发一个系统,该系统为访问我的网站的所有用户生成一个ID。如果用户创建帐户,申请信贷,购买产品等,它将跨数据库上的多个表将具有此ID的用户信息链接起来。我的问题是,合并所有信息需要很长时间,因为到目前为止,我们已拥有超过60,000千条记录。之前,我创建了一个VIEW,它完全浪费了性能(最多3分钟),因此我决定创建一个查询来获取数据,并将非空字段与PHP结合在一起,总共得出10到15分页的时间也是如此。如果可能的话,我希望它可以进一步改进。有什么建议吗?

    SELECT DISTINCT
    u.user_id,
    u.operating_system_name AS os,
    u.browser_name AS browser,
    u.ip_address,
    u.hardware_type AS hardware,
    u.city AS city,
    u.state AS state,
    u.country AS country,
    u.date AS date,

    m.id_member AS member,
    s.id_supplier AS supplier,
    c.id_entry AS credit,
    p.id_partner AS partner,
    cu.employee_ID AS careersus,
    cm.empleado_ID AS careersmx,
    o.id_order     AS orderid,

    o.recipient_name AS fn_o,
    m.first_name AS fn_m,
    c.first_name AS fn_c,
    p.first_name AS fn_p,
    s.contact_first_name AS fn_s,
    cu.firstname AS fn_cu,
    cm.nombre AS fn_cm,

    o.last_name AS ln_o,
    m.last_name AS ln_m,
    c.last_name AS ln_c,
    p.last_name AS ln_p,
    s.contact_last_name AS ln_s,
    cu.lastname AS ln_cu,
    cm.apellido AS ln_cm

    FROM tb_users_ids AS u 
    LEFT JOIN tb_orders AS o ON u.user_id = o.user_id
    LEFT JOIN tb_members AS m ON u.user_id = m.user_id
    LEFT JOIN financing AS c ON c.user_id = u.user_id
    LEFT JOIN tb_partners AS p ON p.user_id = u.user_id
    LEFT JOIN suppliers AS s ON s.user_id = u.user_id
    LEFT JOIN tb_careers_us AS cu ON cu.user_id = u.user_id
    LEFT JOIN tb_careers_mx AS cm ON cm.user_id = u.user_id
    WHERE u.user_id<>''
    ORDER BY u.date DESC
    LIMIT ".$offset.", ".$rowsperpage;

2 个答案:

答案 0 :(得分:1)

您必须创建要比较的所有字段的索引。 因此,如果您的查询类似于table1.user_id = table2.user_id,请在table1和table2中为user_id定义索引。 在所有桌子上都做。

那么它将非常快。

答案 1 :(得分:1)

请使user_id作为所有表的索引。这将使您的查询更快