tags:

views:

23

answers:

1

Using php and mysql,
I have a table "subdomains" that contains subdomains for my application, depending of a category. subdomains - id, cat_id, subdomain

Some categories have subdomain and others don't have. For those that don't have subdomain, I want the subdomain to be 'www'.

Now in my subdomains table there are a few values, for example :

subdomains : id, cat_id, subdomain
             1,  6,   "sales"
             2,  7,   "infos"

Now, I have an array of cat_id, for example $aCatIds = array(1,5,6,8);

At the end of the mysql query I would like a something like this :

array(
0 => (cat_id="1", subdomain="www") ,
1 => (cat_id="5", subdomain="www") ,
2 => (cat_id="6", subdomain="sales") ,
3 => (cat_id="8", subdomain="www") ,
)

Is it possible with only one mysql query ?

I use php and tried things like this :

$stmt = "select cat_id, ifnull('www', subdomain) as subdomain
    from subdomains
    where cat_id in (". implode(',', $aCatIds) .")";

But I only get the values that are set (6 in the above example), and I don't know how to tell mysql to get the expected array.

A: 

To make this work, you'll have to (left) join to existing data (where the cat_id does exist). For instance, if I assume a cat table exists which the cat_id references, 't would be so:

SELECT c.id as cat_id,IFNULL(s.subdomain,'www')
FROM cat c 
LEFT JOIN subdomains s
ON s.cat_id = c.id
WHERE c.id IN (1,2,3,4);
Wrikken
I tried SELECT c.id as cat_id,IFNULL(s.subdomain,'www')FROM cat c LEFT JOIN subdomains sON s.cat_id = c.idWHERE c.id IN (1,5,6,8);But I get just the "cat_id=6" row.
ling
Wrikken
1,5,6 and 8 are all in the cat table.Both cat and subdomains table are of type innoDB.But 1,5 and 8 are not in the result set, I just get 1 single line,with the cat_id=6 and subdomain='sales'
ling
Did you actually use the **LEFT** part of the join? 'Cause if they are in the cat table, this _should_ work.
Wrikken
YES!Man, your guess was right!Me, tired geek, late at night yesterday when transposing your suggestion made a mistake and came up with something like :SELECT s.cat_id as cat_id,IFNULL(s.subdomain,'www') FROM cat c LEFT JOIN subdomains s ON s.cat_id = c.id WHERE s.cat_id IN (1,2,3,4); And of course it doesn't work, but this one that you wrote worked :SELECT c.id as cat_id,IFNULL(s.subdomain,'www') FROM cat c LEFT JOIN subdomains s ON s.cat_id = c.id WHERE c.id IN (1,2,3,4); I get better understanding of mysql query now.Thanx a lot ;)
ling