views:

86

answers:

4

I have two tables: Stores and Items. The relationship is: Stores 1---* Items

In PHP/MySQL what would be the best (fastest/simplest) way to check if a particular item belongs to a particular store.

In other words given for example:

$store_id = 1;
$item_id = 12;

I want to check if item 12 belongs to store 1 (and not some other store).

I usually do a select on Items matching both the store_id and item_id and limit the results to 1. Then check how many rows (0 or 1) were returned with mysql_num_rows. Is there a better way?

Update:

Both tables have an "id" column. The Items table has a "store_id" column.

A: 
$r = mysql_query("select NULL from Item where storeID = '$store_id' and ItemID = '$item_id'");

if (mysql_fetch_row($r))
{
    it belongs...
}
Francisco Soto
Thanks. That's pretty much what I do, except for checking mysql_fetch_row instead of mysql_num_rows. Is there an advantage to one over the other?
Nebs
No advantage. In both cases query will be executed in the same manner and data received.
zerkms
+2  A: 
SELECT COUNT(*) AS count
FROM stores JOIN items USING(store_id)
WHERE item_id = 12
  AND store_id = 1

Then you'd get the results, and check of count > 0 or not. However, if I'm getting your DB design right, then you have a very messed up database.

From what you describe, an item can only exist in one store. So my guess of the general layout here would be like this:

STORE            ITEM
-----            ----
store_id ---|    item_id
store_name  |--- store_id
...              item_name
                 ...

Is this correct? An item can never exist except in the one store? So if it's a screwdriver, every store would need a different item_id to hold it?

A better design would be:

STORE            STORE_ITEM         ITEM
-----            ----------         ----
store_id ------- store_id   |------ item_id
store_name       item_id ---|       item_name
...                                 ...

With a query of

SELECT COUNT(*)
FROM store JOIN store_item USING(store_id)
     JOIN item USING(item_id)
WHERE store_id = 1
  AND item_id = 12
Slokun
even if you guessed the schema right - why do we need in 2 joins just for count? why not just select count(*) from STORE_ITEM?
zerkms
hehe, guessed wrong ;-P
zerkms
Slokun
+1  A: 

Both tables have an id, Items has a store_id

SELECT COUNT(*) FROM Items WHERE store_id = $store_id AND id = $item_id
zerkms
A: 

For fun, I'll throw in a one-liner check:

// if item belongs to store
if (current(mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM Items WHERE store_id = $store_id AND id = $item_id"), MYSQL_NUM)))) {
    // it belongs!
}
webbiedave