There are 3 tables in the database. All 3 tables have the same "booster" field. The point is that I need to calculate ONE query the number of "booster" fields using COUNT (), in all 3 tables through the WHERE operator.

It’s not necessary to do this with 3 queries of the mind, but I don’t have enough knowledge of SQL to make one I managed to do it without COUNT (), but without it there is no point.

I enclose an example of my working bydlokod:

include_once $_SERVER['DOCUMENT_ROOT'] . '/engine/includes/db.inc.php'; session_start(); //BEGIN БЫДЛОКОД!!! try { $sql = 'SELECT COUNT(booster) FROM boost_orders WHERE booster = :booster'; $s = $pdo->prepare($sql); $s->bindValue(':booster', $_SESSION['login']); $s->execute(); } catch (PDOException $e) { $error = 'Forbidden 353!!!'; include $_SERVER['DOCUMENT_ROOT'] . '/engine/includes/errors.inc.php'; exit(); } $row_1 = $s->fetchColumn(); try { $sql = 'SELECT COUNT(booster) FROM сalibr_orders WHERE booster = :booster'; $s = $pdo->prepare($sql); $s->bindValue(':booster', $_SESSION['login']); $s->execute(); } catch (PDOException $e) { $error = 'Forbidden 353!!!'; include $_SERVER['DOCUMENT_ROOT'] . '/engine/includes/errors.inc.php'; exit(); } $row_2 = $s->fetchColumn(); try { $sql = 'SELECT COUNT(booster) FROM lp_orders WHERE booster = :booster'; $s = $pdo->prepare($sql); $s->bindValue(':booster', $_SESSION['login']); $s->execute(); } catch (PDOException $e) { $error = 'Forbidden 353!!!'; include $_SERVER['DOCUMENT_ROOT'] . '/engine/includes/errors.inc.php'; exit(); } $row_3 = $s->fetchColumn(); $total = $row_1 + $row_2 + $row_3; if ($total >= 1) { $error = 'Вы не можете брать больше одного заказа!'; include $_SERVER['DOCUMENT_ROOT'] . '/engine/includes/errors.inc.php'; exit(); } //END БЫДЛОКОД!!! 
  • if ($total >= 1) - this could simplify everything. - vp_arth

1 answer 1

You need to use the UNION ALL operator in order to glue the samples into 3 tables, and you should already apply COUNT to the glued table:

 select COUNT(*) from (SELECT booster from t1 where booster = :booster UNION ALL SELECT booster from t2 where booster = :booster UNION ALL SELECT booster from t3 where booster = :booster) as query 

In any normal database with ANSI SQL support will work.

  • Yes, everything works fine. Thank you very much. - Demian Shumilov