Sample Data :
| ad_id | ad_type | duration | page | common | sorter | |-------|---------|----------|---------------|--------|--------| | 20 | center | 2 | | false | 0 | | 21 | left | 5 | | false | 0 | | 19 | left | 1 | | false | 0 | | 18 | head | 2 | | true | 0 | | 17 | right1 | 4 | | true | 1 | | 16 | right1 | 5 | | false | 0 | | 22 | center | 3 | | true | 0 | | 23 | head | 6 | | true | 0 | | 25 | head | 2 | | false | 0 | | 29 | left | 5 | | false | 0 | | 30 | left | 7 | | false | 0 | | 32 | head | 4 | 1494573224714 | false | 2 | | 33 | left | 5 | 1494573224714 | false | 2 | | 34 | left | 1 | 1494573224714 | false | 2 | | 35 | left | 9 | 1494066642553 | false | 1 | | 36 | left | 10 | 1494066642553 | false | 3 | | 38 | head | 5 | 1494066642553 | false | 1 |
and desired output :
| ad_type | GROUP_CONCAT( duration ORDER BY sorter ASC SEPARATOR ' , ') | |---------|-------------------------------------------------------------| | head | 4 | | center | 3 | | right1 | 4 | | left | 1 , 5 |
http://sqlfiddle.com/#!9/e67161/1
I'm using the following query:
select ad_type, GROUP_CONCAT( duration ORDER BY sorter ASC SEPARATOR ' , ') from ad WHERE ad_type='head' AND IF( EXISTS (SELECT 1 FROM ad where page='1494573224714' AND ad_type='head') , page='1494573224714', common=1 ) group by ad_type UNION select ad_type, GROUP_CONCAT( duration ORDER BY sorter ASC SEPARATOR ' , ') from ad WHERE ad_type='center' AND IF( EXISTS (SELECT 1 FROM ad where page='1494573224714' AND ad_type='center') , page='1494573224714', common=1 ) group by ad_type UNION select ad_type, GROUP_CONCAT( duration ORDER BY sorter ASC SEPARATOR ' , ') from ad WHERE ad_type='left' AND IF( EXISTS (SELECT 1 FROM ad where page='1494573224714' AND ad_type='left') , page='1494573224714', common=1 ) group by ad_type
Is there a way something like IN('head','left','right1','center')
or to perform on all distinct ad_type
?
The Query I'd used that failed :
select ad_type, GROUP_CONCAT( duration ORDER BY sorter ASC SEPARATOR ' , ') from ad WHERE IF( EXISTS (SELECT 1 FROM ad where page='1494573224714') , page='1494573224714', common=1 ) group by ad_type
Which returns :
| ad_type | GROUP_CONCAT( duration ORDER BY sorter ASC SEPARATOR ' , ') | |---------|-------------------------------------------------------------| | head | 4 | | left | 1 , 5 |
I want the condition to get applied on each group so that I get results with 'center' ad_type as common=1 etc...
duration : 0 common : 0
, or something else?select concat(ad_type,'Ad') as c1,GROUP_CONCAT( concat('<div class="',ad_type,'Ad" alt=',duration,'><a href="',ad_link,'" target="_blank"><img src="',img_location,'" width="100%" height="100px"/><span class="w3-small w3-text-grey w3-left">',ad_title,'<br/></span></a></div>') ORDER BY sorter ASC SEPARATOR '') as c2
which I thought would waste readers time so I simplified it. Previously I was doing it in the program code i.e. select statement in a loop which I read is bad thing to do.