如何在Yii中用MySQL编写此查询?
Yii::app()->db->createCommand()
->select("C.[id], C.[name], C.[family], C.[mobile]
, Stuff((
SELECT ', ' + (contact_group.name)
FROM contact_grouping AS CGG , contact_group
WHERE CGG.contact = C.Id AND CGG.[group] = contact_group.id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS [groups]")
->from("contact AS c")
->where("C.[user] = {$UID} AND C.[attr] = ".self::ATTR_NORMAL.$con)
答案 0 :(得分:0)
您正在寻找GROUP_CONCAT
。您的查询可能看起来像
Yii::app()->db->createCommand()
->select("c.id, c.name, c.family, c.mobile,
(SELECT GROUP_CONCAT(g.name)
FROM contact_grouping gg JOIN contact_group g
ON g.id = gg.`group`
WHERE gg.contact = c.id
GROUP BY gg.contact) groups")
->from("contact c")
->where("c.user = {$UID} AND c.attr = ".self::ATTR_NORMAL.$con)
未经过测试