检查所选项目列表是否在另一个表中

时间:2011-06-14 14:58:40

标签: php mysql

我试图想出一些代码来检查用户是否拥有项目列表。项目列表可以是任意长度,但可能不超过5个。

这里涉及2个表:qrequirements和inventory。

我已经运行循环来检查用户是否拥有每个项目,但我仍然坚持如何记录每个项目的所有权结果以及之后如何将其传达给用户。< / p>

我可能会以错误的方式解决这个问题,也许有一种更简单的方法,我不知道。

任何帮助都会很棒。到目前为止,这是我的代码:

<?php

// Get the list of required items
$result = mysql_query("select * from qrequirements where qid='2'");
// This might return E.G:
// item1 = '32'
// item2 = '24'
// item3 = '15'

// Loop through each item to check the user has it
while ($row = mysql_fetch_array($result)) {
    $itemid = $row["itemid"];
    $check_inv = mysql_query("select * from inventory where userid='$userid' AND item = $itemid");
    $num_rows = mysql_num_rows($check_inv);
    if($num_rows>=1){
        // Something in here to confirm the item is owned by the user, while we check the others
    }else{
        echo "You do not have this item";
    }
}

// Notify the user if they have all items required

?>

2 个答案:

答案 0 :(得分:0)

确定用户需要但没有的项目可以通过单个查询来解决。以下查询应该完成该任务。

SELECT * FROM qrequirements t1
 WHERE t1.quid = '2'
   AND NOT EXISTS ( SELECT 1 FROM inventory t2
                 WHERE t1.item = t2.item
                   AND t2.userid = '$userid')

如果您还需要知道用户拥有哪些项目,那么此类似查询将完成该额外任务。

SELECT * FROM qrequirements t1
 WHERE t1.quid = '2'
   AND EXISTS ( SELECT 1 FROM inventory t2
                 WHERE t1.item = t2.item
                   AND t2.userid = '$userid')

另一个有用的查询是返回所需项目以及用户是否拥有该项目的指示。如果用户没有该项,则item_count将为0;如果用户具有该项,则item_count将大于0。

SELECT t1.*, (SELECT count(*) FROM inventory t2
               WHERE t1.item = t2.item
                 AND t2.userid = '$userid') as item_count
 FROM qrequirements t1
WHERE t1.quid = '2'

答案 1 :(得分:0)

尝试将其作为仅限SQL的版本:

SELECT IF(COUNT(DISTINCT r.itemid) = COUNT(DISTINCT i.itemid), 1, 0) as met_reqirements
FROM qrequirements r
    LEFT JOIN inventory i ON i.itemid = r.item_id AND i.userid = '$userid'
WHERE r.qid = 2