Search code examples
phpmysqlbelongs-to

PHP/MySQL: Check if something 'belongs-to' something else?


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.


Solution

  • 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