【问题标题】:PHP MySQL join one table with another one but twicePHP MySQL将一张表与另一张表连接两次
【发布时间】:2015-09-01 11:14:48
【问题描述】:

我正在尝试加入两张桌子,但最后一张是两次。 我得到的是这样的:

Table 1
    id name email
    476 Lars Lyngsoe   test@test.test
    478 Lars2 Lyngsoe2 test2@test2.test2
    495 Lars3 Lyngso3  test3@test3.test3

Table 2
    user_id  profile_key      profile_value
    476     'profile.klasse'  '10A'
    495     'profile.klasse'  '10B'
    476     'profile.phone'   '12345678'
    478     'profile.klasse'  '10A'
    478     'profile.phone'   '23432123'
    495     'profile.phone'   '21212143'

其中表 1 中的 id 等于表 2 中的 user_id

我尝试加入并进行子查询,但没有任何效果。 我想要实现的是:

Table
    id  name           email              class  phone
    476 Lars Lyngsoe   test@test.test     '10A'  '12345678'
    478 Lars2 Lyngsoe2 test2@test2.test2  '10A'  '23432123' 
    495 Lars3 Lyngso3  test3@test3.test3  '10B'  '21212143'

感谢您的帮助。

拉尔斯

【问题讨论】:

  • 在问题中包含您尝试过的查询。
  • 你的电话号码是从哪里得到的?
  • 而不是加入两次反转联接,因此表 2 是您的主表,然后针对 tbl 1 为每个用户 id 进行内部联接,因此每条记录返回多行然后只是 where 子句 tbl1.user_id 与传入的 id它会返回你想要的。

标签: php mysql join subquery


【解决方案1】:

这应该可行:

SELECT t1.id as id, t1.name, t1.email, t2a.profile_value as class, t2b.profile_value as phone
FROM Table1 as t1
LEFT JOIN Table2 t2a ON t2a.user_id = t1.id AND t2a.profile_key = 'profile.klasse'
LEFT JOIN Table2 t2b ON t2b.user_id = t1.id AND t2b.profile_key = 'profile.phone'

【讨论】:

  • AFAICR 在 MySQL 上,表别名可能需要 AS 关键字。 LEFT JOIN Table2 AS t2a 但我不确定了
  • 你说得对,我应该再看一遍,修复它
  • @Eloims 你的回忆有问题
  • 非常感谢您的帮助!如果我只想显示 profile_value 等于“10A”的行怎么办 - 谢谢!
【解决方案2】:

您需要的是两个具有特定 profile_key 值的联接:

SELECT t1.id, t1.name, t1.email, t2.profile_value AS class, t3.provile_value AS phone
FROM Table1 t1
LEFT JOIN Table2 t2 ON (t1.id = t2.user_id AND t2.profile_key='profile.klasse')
LEFT JOIN Table2 t3 ON (t1.id = t3.user_id AND t3.profile_key='profile.phone')

【讨论】:

    【解决方案3】:

    我已经为您编写了一个数据库查询。希望能解决你的问题:

    查询

    SELECT 
        t1.id,
        t1.`name`,
        t1.email,
        CASE t2.profile_key
            WHEN 'profile.klasse' THEN t2.profile_value
        END AS 'class',
        (SELECT profile_value FROM table2 WHERE profile_key = 'profile.phone' AND user_id = t1.id) AS 'phone'
    FROM
        table1 t1
            LEFT JOIN
        table2 t2 ON t1.id = t2.user_id AND t2.profile_key = 'profile.klasse' ORDER BY id;
    

    点击SQL Fiddle

    【讨论】:

    • 非常感谢 - 我会考虑你的建议。
    • 如果我想显示 profile_value 等于 '10A' 的行怎么办? - 谢谢
    【解决方案4】:

    或者,更慢但更简单......

    SELECT t1.*
         , MAX(CASE WHEN t2.profile_key = 'profile.klasse' THEN t2.profile_value END) klasse
         , MAX(CASE WHEN t2.profile_key = 'profile.phone' THEN t2.profile_value END) phone
      FROM t1
      JOIN t2 
        ON t2.user_id = t1.user_id
     GROUP
        BY t1.user_id
    

    【讨论】: