How to count records in more than one table?

Asked

Viewed 42 times

-3

I have these 3 tables:

client clientVehicle parking

I want to mount a SELECT that counts the number of records for each of them.

SELECT
   COUNT(client.idClient) AS clientQuantity,
   COUNT(clientVehicle.idClientVehicle) AS clientVehicle, 
   COUNT(parking.idParking) AS parkingQuantity 
FROM 
    client,
    clientVehicle,
    parking
WHERE
    client.idClient AND
    clientVehicle.idClientVehicle AND 
    parking.idParking

However, the result is 4 for all, and it should be, parkingQuantity 1, clientQuantity2 and clientVehicles 2. Where I’m wrong?

Thank you very much.

  • Remove the clause WHERE

  • no Join there, you added 4 tables in FROM and does not link them, will return a cartesiado of all, and everything will have the same value!

3 answers

0

Just looking at her SELECT and what he tried to do in WHERE, which was supposed to be the JOIN between the tables, I can suggest this SELECT:

SELECT COUNT(client.idClient) AS clientQuantity, 
       COUNT(clientVehicle.idClientVehicle) AS clientVehicle, 
       COUNT(parking.idParking) AS parkingQuantity 
  FROM client
 INNER JOIN clientVehicle ON client.idClient = clientVehicle.idClient
 INNER JOIN parking ON parking.parkingPass = client.parkingPass

Note that in the table "Parking", supposedly the JOIN should be by the column "idParking", but by the photo of your model I did not identify relative column in any of the tables, so I did the JOIN by "parkingPass"

  • Ricardo, I ran your SQL and return 1 in each of the values, that is, not given yet.

  • No no, parkingPass has nothing to connect.

  • Without an example of the data, you can’t help much more. Create an example here http:/sqlfiddle.com/ with tables and some sample data to show what doesn’t work

-1

I found a solution

SELECT  (
    SELECT COUNT(*)
    FROM   client
    ) AS qttClient,
    (
    SELECT COUNT(*)
    FROM   parking
    ) AS qttParking,
    (
    SELECT COUNT(*)
    FROM   clientVehicle
    ) AS qttClientVehicle
FROM    dual

inserir a descrição da imagem aqui

-2

Enjoying the friend’s select already published in the post, you can replace the * by the numerical position of the column you want to count, in these cases where you want the ID columns that are the first the answer is as follows:

SELECT ( SELECT COUNT(1) FROM client ) AS qttClient, ( SELECT COUNT(1) FROM Parking ) AS qttParking, ( SELECT COUNT(1) FROM clientVehicle ) AS qttClientVehicle FROM dual

Browser other questions tagged

You are not signed in. Login or sign up in order to post.