计算用户是否已达到借款限额

时间:2013-05-23 14:21:42

标签: mysql sql

我设置了表格和数据的小提琴here

我正在尝试编写单个sql以检查用户是否已达到每个类别的借用限制。

现在,它已经完成了使用几个相互调用的sql语句。

但它的方式很简单。 memId和id来自一个查询字符串。

$medId = $_POST['memId']; Using 1 for this example. This is the members Id.
$id = $_POST['id']; Using 4 for this example. This is the item being lent.

之后我做了:

select id, holder from collection_db where id = 4 // We have a valid item

select borrowMax from collection_db where id = (holder from the previous select) and category = 10 //Result = 2. Category indicates its a label and not a borrowable item.

select count(borrowedId) from lendings where memId = 1 and holder = (holder from the 1st query) //He's borrowed 2, under 1, so cant borrow any more. User 2 may borrow however.

if (count => borrowMax) {echo 'Cannot borrow more.';} else {echo 'Added to'}

如何将它组合成单个sql,还是最好这样做?

2 个答案:

答案 0 :(得分:1)

这似乎产生了正确的结果集:

SELECT col1.id, col1.holder, col2.borrowMax, count(lend.borrowedId) as `count`
FROM collection_db col1
  INNER JOIN collection_db col2
  ON col1.holder = col2.id
    INNER JOIN lendings lend
    ON col1.holder = lend.holder
WHERE col1.id = $id
AND col2.category = 10
AND lend.memId = $medId

答案 1 :(得分:0)

我认为这结合了查询:

select max(c.borrowMax) as BorrowMax, COUNT(*)
from collection_db c join
     collection_db c1
     on c.id = c1.holder and c1.id = 4 and c.category = 10 join
     lendings l
     on l.holder = c1.holder;

它确实假设cc1之间的连接不会产生重复的行。但是,您可以在原始查询中使用=(而不是join)来满足此要求。