我需要一些帮助来构建查询并将结果合并为一行,这是表格:
tbl_contacts
id | name | lastname | email
1 | daniel1| lastname1 | daniel1@test.com
2 | daniel2| lastname2 | daniel2@test.com
tbl_contacts_var
cid | name | value|
1 | VAR1 | d1 |
1 | VAR2 | d2 |
1 | VAR3 | d3 |
我尝试了以下查询,这是我可以获得的最接近的期望结果,但是我需要不同的地方,这是我尝试过的:
SELECT tbl_contacts.*,
( SELECT GROUP_CONCAT(value SEPARATOR ',')
FROM tbl_contacts_var WHERE
tbl_contacts.id = tbl_contacts_var.cid )
as attributes
FROM tbl_contacts WHERE tbl_contacts.id = 1
这是输出
id | name | lastname | email |attributes
1 | daniel1| lastname1 | daniel1@test.com|d1,d2,d3
但是,我正在寻找的输出更像这样:
id | name | lastname | email | VAR1 | VAR2 | VAR3 |
1 | daniel1| lastname1 | daniel1@test.com| d1 | d2 | d3 |
我尝试使用JOIN,但它返回三行,并且我需要在一行中显示完整结果,还需要在第二张表中将“ name”的值用作结果的列名,这可能吗?
我将不胜感激,谢谢!
答案 0 :(得分:0)
您可以在下面尝试查询
SELECT c.name, c.name, c.lastname, c.email
, MAX(
CASE cv.name
WHEN 'VAR1' THEN cv.VALUE
ELSE NULL
END
) AS VAR1
, MAX(
CASE cv.name
WHEN 'VAR2' THEN cv.VALUE
ELSE NULL
END
) AS VAR2
, MAX(
CASE cv.name
WHEN 'VAR3' THEN cv.VALUE
ELSE NULL
END
) AS VAR3
FROM tbl_contacts c
JOIN tbl_contacts_var cv ON cv.cid = c.id
GROUP BY c.name, c.name, c.lastname, c.email