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 に答える