0

我在这里有一个问题......我有3张这样的桌子......

顾客

idCustomer | namaCustomer | email   | noTelp 
__________________________________________________
1          |  Wawan       | a@a.com | 08985623895

属性

idAttribute | Name   | publish
______________________________
1           | Gender |  Y
2           | Hobby  |  Y
3           | Job    |  Y
4           | Mission|  N

客户属性

idCustomer  |  idAttribute   | value 
_____________________________________
1           |   1            | Male
1           |   2            | Hacking
1           |   3            | IT Support

问题是.. 如果我想从这 3 个表中获取查询并得到这样的结果,应该使用什么查询语句

idCustomer | namaCustomer | email   | noTelp      | Gender  | Hobby   | Job
___________________________________________________________________________________
1          |  Wawan       | a@a.com | 08985623895 | Male    | Hacking | IT Support

所以表列是从客户属性数据中添加的,但在此之前我们必须查看属性表,该属性是否已发布(查找发布值)

任何人都可以在这里帮助我???

非常感谢之前

4

1 回答 1

3

试试这个:

SELECT
  c.idCustomer,
  c.namaCustomer,
  c.email,
  c.noTelp, 
  MAX(CASE WHEN a.Name = 'Gender' THEN ca.value END) AS 'Gender',
  MAX(CASE WHEN a.Name = 'Hobby'  THEN ca.value END) AS 'Hobby',
  MAX(CASE WHEN a.Name = 'Job'    THEN ca.value END) AS 'Job'
FROM Customerattribute ca
INNER JOIN attribute a ON ca.idAttribute = a.idAttribute
INNER JOIN Customer c ON c.idCustomer = ca.idCustomer
GROUP BY ca.idCustomer

SQL 小提琴演示

但是,为了将来将此查询用于新属性,您必须像这样动态地执行此操作:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(a.Name = ''',
      a.Name, ''', ca.value, NULL)) AS ',
      a.Name )
  ) INTO @sql
FROM Customerattribute ca
INNER JOIN attribute a ON ca.idAttribute = a.idAttribute
INNER JOIN Customer c ON c.idCustomer = ca.idCustomer
WHERE a.publish = 'Y';

SET @sql = CONCAT('SELECT  c.idCustomer,  c.namaCustomer, '
  ' c.email, c.noTelp, ', @sql, ' FROM Customerattribute ca',
 ' INNER JOIN attribute a ON ca.idAttribute = a.idAttribute', 
' INNER JOIN Customer c ON c.idCustomer = ca.idCustomer',
' GROUP BY c.idCustomer');

SELECT @sql;

prepare stmt 
FROM @sql;

execute stmt;

动态小提琴演示

于 2012-11-03T03:49:24.877 回答