我正在尝试加入两个表,但最后一个表加两次。 我得到的是:
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'
感谢您的帮助。
拉斯
答案 0 :(得分:1)
这应该有效:
select
order0_.orderId as orderId1_1_,
order0_.customer_customerId as customer_s10_1_,
from
Order order0_
cross join Customer customer1_
where
order0_.customer_customerId=customer1_.customerId
and
(customer1_.status in (? , ? , ? , ? , ? , ? , ? , ?))
答案 1 :(得分:0)
您需要的是具有特定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')
答案 2 :(得分:0)
我已经为您编写了数据库查询。我希望它能解决你的问题:
<强>查询强>
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;
答案 3 :(得分:0)
或者,更慢但更简单...
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