简体   繁体   English

计算用户是否达到了舷梯限制

[英]Count if a user has reached the borrwing limit

I've setup a fiddle with tables and data here 我设置一个拨弄表和数据在这里

I'm trying to write a single sql to check if user has reached the borrowing limit for each category. 我正在尝试编写单个sql以检查用户是否已达到每个类别的借用限制。

Right now, it's done using severals sql statements called after each other. 现在,它已经完成了使用几个相互调用的sql语句。

But the way it goes is simple. 但它的方式很简单。 memId and id come through a querystring. 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.

After that I do: 之后我做了:

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'}

How can this be combined into a single sql or is it best left this way? 如何将它组合成单个sql或者最好是这样?

This seems to produce a correct result set: 这似乎产生了一个正确的结果集:

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

I think this combines the queries: 我认为这结合了查询:

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;

It does make an assumption that the join between c and c1 does not produce duplicate rows. 它确实假设cc1之间的连接不会产生重复的行。 But you have this requirement by using = in the original query (rather than join ). 但是在原始查询中使用= (而不是join )可以满足此要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM