0

我有两张桌子:商店和物品。关系是:Stores 1---* Items

在 PHP/MySQL 中,检查特定商品是否属于特定商店的最佳(最快/最简单)方法是什么。

换句话说,例如:

$store_id = 1;
$item_id = 12;

我想检查项目 12 是否属于商店 1(而不是其他商店)。

我通常对同时匹配 store_id 和 item_id 的项目进行选择,并将结果限制为 1。然后检查 mysql_num_rows 返回了多少行(0 或 1)。有没有更好的办法?

更新:

两个表都有一个“id”列。Items 表有一个“store_id”列。

4

4 回答 4

2
SELECT COUNT(*) AS count
FROM stores JOIN items USING(store_id)
WHERE item_id = 12
  AND store_id = 1

然后你会得到结果,并检查count > 0与否。但是,如果我让您的数据库设计正确,那么您的数据库非常混乱。

根据您的描述,一件商品只能存在于一家商店中。所以我对这里的总体布局的猜测是这样的:

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

这个对吗?一件商品永远不会存在,除非在一个商店里?所以如果是螺丝刀,每个商店都需要不同item_id的来握它吗?

更好的设计是:

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

查询

SELECT COUNT(*)
FROM store JOIN store_item USING(store_id)
     JOIN item USING(item_id)
WHERE store_id = 1
  AND item_id = 12
于 2010-04-29T21:08:47.637 回答
1

两个表都有一个 id,Items 有一个 store_id

SELECT COUNT(*) FROM Items WHERE store_id = $store_id AND id = $item_id
于 2010-04-29T21:13:20.550 回答
0

为了好玩,我将进行单行检查:

// 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!
}
于 2010-04-29T21:33:15.273 回答
0
$r = mysql_query("select NULL from Item where storeID = '$store_id' and ItemID = '$item_id'");

if (mysql_fetch_row($r))
{
    it belongs...
}
于 2010-04-29T21:07:01.767 回答