5

我在这里设置了表格和数据的小提琴

我正在尝试编写一个 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 或者最好这样保留?

4

2 回答 2

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
于 2013-05-23T15:47:23.763 回答
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;

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

于 2013-05-23T14:29:58.113 回答