PHP MySQL 加入一个 table 与另一个但两次

PHP MySQL join one table with another one but twice

我正在尝试连接两个表,但最后一个表连接了两次。 我得到的是:

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'

其中 id in Table 1 等于 user_id in Table 2

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

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'

感谢您的帮助。

拉斯

这应该有效:

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'

您需要的是两个具有特定 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')

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

查询

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

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

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