select id from banners A ,(select count(*) AS cnt from banners where device LIKE '%ios%') B
WHERE
device LIKE (case when B. cnt = 0 then '%%' else '%ios%' end)
ORDER BY RAND() LIMIT 1
mysql where clause to show banner based on device
-
30-06-2023 - |
Question
I have a mysql table "banners" with a column "device" in it
the column "device" is NULL if the banner is for desktop, and is "ios" if the banner is for iphone/ipad device.
now i'm working on a script to show the banner based on device..
for example if someone visit the website with a desktop the query is:
SELECT id FROM banners WHERE 1 ORDER BY RAND() LIMIT 1
and if i visit the website with an iphone the query change:
SELECT id FROM banners WHERE device LIKE '%ios%' ORDER BY RAND() LIMIT 1
Everything works fine, except that if i have 0 banners for IOS i would to show a DESKTOP banner instead of nothing, but i don't know how to change the query..
for example if i add a OR clause the priority of IOS remain???
SELECT id FROM banners WHERE ( device LIKE '%ios%' OR device ='') ORDER BY RAND() LIMIT 1
Solution
OTHER TIPS
There is a difference between a database NULL
and the empty string, which is what I think your stumbling on here. Try this:
SELECT id FROM banners WHERE ( device LIKE '%ios%' OR device IS NULL) ORDER BY RAND() LIMIT 1
See this bit of the MySQL website for information on working with NULL
values in MySQL