关于某人是否喜欢水果的布尔列

时间:2017-02-21 09:01:44

标签: mysql

我有这三个表:

person:
id  name           
1   John Norberg                
2   Mary Kelly           
3   Joseph Fritz

fruit_preference_mapping: 
person_id   fruit_id 
1           1
1           2
2           3

fruit:
id  name           
1   Apple                
2   Banana           
3   Orange

什么mysql语句会产生以下输出:

person_name   Apple   Banana    Orange            
John Norberg   true    true      false             
Mary Kelly     false   false     true      
Joseph Fritz   false   false     false

就我而言:

select person.name form person 
left join fruit_preference_mapping 
on person.id = fruit_preference_mapping.person_id 
left join fruit 
on fruit_preference_mapping.fruit_id = fruit.id;

1 个答案:

答案 0 :(得分:2)

你基本上要求一个支点。试试这个:

   SELECT p.name AS person_name
        , IF(SUM(f.name = 'Apple'), 'true', 'false') AS Apple
        , IF(SUM(f.name = 'Banana'), 'true', 'false') AS Banana
        , IF(SUM(f.name = 'Orange'), 'true', 'false') AS Orange
     FROM person p
LEFT JOIN fruit_preference_mapping m ON m.person_id = p.id
LEFT JOIN fruit f ON f.id = m.fruit_id
 GROUP BY p.name;

SQL Fiddle

相关问题