我在MySQL Workbench中创建了一个视图:
表格
我想创建一个视图,以这样的方式返回记录,我从 addressBook 表&获取所有行数据字段值以逗号分隔 addressBookData 表。
怎么做?
我的观点是这样的:
CREATE VIEW `addressBook_view` AS
SELECT
`addressBook`.*,
(SELECT `addressBookData`.`data` FROM `addressBookData` WHERE `addressBook_id` = `id` AND `type` = 'mobile') AS `mobile`,
(SELECT `addressBookData`.`data` FROM `addressBookData` WHERE `addressBook_id` = `id` AND `type` = 'phone') AS `phone`,
(SELECT `addressBookData`.`data` FROM `addressBookData` WHERE `addressBook_id` = `id` AND `type` = 'fax') AS `fax`
FROM
`addressBook`
答案 0 :(得分:1)
尝试这样的事情:
SELECT ab.*, abd.type, GROUP_CONCAT(abd.data SEPARATOR ',')
FROM addressBook ab
LEFT JOIN addressBookData abd ON ab.id = abd.addressBook_id
GROUP BY ab.id, abd.type
您可以自己创建基于此查询的视图。
答案 1 :(得分:0)
结束这样做:
CREATE VIEW `addressBook_view` AS
SELECT
`addressBook`.*
(SELECT GROUP_CONCAT(`data`) FROM `addressBookData` WHERE `addressBook_id` = `addressBook`.`id` AND `type` = 'mobile' GROUP BY `id`) AS `mobile`,
(SELECT GROUP_CONCAT(`data`) FROM `addressBookData` WHERE `addressBook_id` = `addressBook`.`id` AND `type` = 'phone' GROUP BY `id`) AS `phone`,
(SELECT GROUP_CONCAT(`data`) FROM `addressBookData` WHERE `addressBook_id` = `addressBook`.`id` AND `type` = 'fax' GROUP BY `id`) AS `fax`
FROM
`addressBook`