我是MySQL的新手,但我已经设法找到了我想要做的两件事的个别解决方案,现在我只需要帮助将它们组合起来。
我有一个包含两个表的数据库:Users和user_profile。我设法创建了一个查询,它将来自两个表的数据组合成一个表,其中包含以下内容:
select t1.id,
t1.name,
max(case when t2.`profile_key` = 'profile.address1' then t2.profile_value end) address,
max(case when t2.`profile_key` = 'profile.city' then t2.profile_value end) city,
max(case when t2.`profile_key` = 'profile.postal_code' then t2.profile_value end) postal_code,
max(case when t2.`profile_key` = 'profile.phone' then t2.profile_value end) phone
from users t1
left join user_profiles t2
on t1.id = t2.user_id
group by t1.id, t1.name
我还要分享"名称"列成"名字"和"姓氏"所以我可以按姓氏排序。我可以用这个来实现这个目标:
SELECT IF(
LOCATE(' ', `name`) > 0,
SUBSTRING(`name`, 1, LOCATE(' ', `name`) - 1),
`name`
) AS memberfirst,
IF(
LOCATE(' ', `name`) > 0,
SUBSTRING(`name`, LOCATE(' ', `name`) + 1),
NULL
) AS memberlast
FROM `users`;
有没有办法将这些问题合并为一个?
答案 0 :(得分:0)
UNION SELECT,row1_name,row2_name,FROM tbl_name应该可以解决问题,不能记住语法是否正确但是查询是联合:)
答案 1 :(得分:0)
我想我明白你需要姓名而不只是名字,所以试试这个:
SELECT t1.id,
IF(
LOCATE(' ', t1.name) > 0,
SUBSTRING(t1.name, 1, LOCATE(' ', t1.name) - 1),
t1.name
) AS memberfirst,
IF(
LOCATE(' ', t1.name) > 0,
SUBSTRING(t1.name, LOCATE(' ', t1.name) + 1),
NULL
) AS memberlast ,
MAX(CASE WHEN t2.`profile_key` = 'profile.address1' THEN t2.profile_value END) address,
MAX(CASE WHEN t2.`profile_key` = 'profile.city' THEN t2.profile_value END) city,
MAX(CASE WHEN t2.`profile_key` = 'profile.postal_code' THEN t2.profile_value END) postal_code,
MAX(CASE WHEN t2.`profile_key` = 'profile.phone' THEN t2.profile_value END) phone
FROM users t1
LEFT JOIN user_profiles t2
ON t1.id = t2.user_id
GROUP BY t1.id, t1.name