3
I have the following tables:
CREATE TABLE IF NOT EXISTS `categoria` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `nome` VARCHAR(25) NOT NULL,
  `descricao` VARCHAR(100) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `veiculo` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `cat_id` INT NOT NULL,
  `modelo` VARCHAR(100) NULL,
  `placa` VARCHAR(7) NULL,
  PRIMARY KEY (`id`),
  INDEX `cat_id` (`cat_id` ASC),
  CONSTRAINT `cat_id`
    FOREIGN KEY (`cat_id`)
    REFERENCES `categoria` (`id`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `locacao` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `veiculo_id` INT NOT NULL,
  `dt_inicio` DATETIME NOT NULL,
  `dt_fim` DATETIME NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `veiculo_id` (`veiculo_id` ASC),
  CONSTRAINT `veiculo_id`
    FOREIGN KEY (`veiculo_id`)
    REFERENCES `veiculo` (`id`))
ENGINE = InnoDB;
I would like to consult all categories and the count of each vehicle in each .. hence I built this query:
SELECT c.nome, count(c.id) AS disponiveis
FROM categoria AS c
INNER JOIN veiculo AS v
ON v.cat_id = c.id
GROUP BY c.id;
that returns me this:
nome, disponiveis
A - ECONÔMICO, 5
B - ECONÔMICO COM AR, 4
C - SEDAN COM AR, 2
Hence I need now that column available return me only vehicles that are not or will be leased in a period > dt_start and < dt_end, but I could not.
Someone can give me a light of where to go?
I tried to this but it did not go as expected. It continued returning all vehicles, until those that will be leased in a period X.
It even solved my problem of researching vehicles in a category that are not leased. I only added in the WHERE of the first query the AND cat_id = 1 LIMIT 1. Thanks.
– Whatyson Neves