如何将第三个条件放入mysql查询

时间:2018-12-08 18:48:16

标签: mysql sql

如何在生产者至少有10辆售出汽车的情况下实现此查询?

SELECT
    *
FROM
    `car`
INNER JOIN
    producer ON car.producer = producer.id
INNER JOIN
    owner ON car.owner = owner.id
WHERE
    owner.email IS NOT NULL
AND
    producer.email IS NOT NULL
AND
    owner.birth_date >= car.produce_year

这三个表是:

TABLE car
id integer
owner integer
color varchar
type varchar 
producer integer
poduce_time integer

TABLE owner
id integer
first name varchar
last name varchar
address varchar
date_of_birth integer
place_of_birth varchar
email varchar

TABLE producer
id integer
name varchar
address varchar
email varchar

2 个答案:

答案 0 :(得分:2)

您必须使用COUNT

SELECT
    *
FROM
    car c
INNER JOIN
    producer ON c.producer = producer.id
INNER JOIN
    owner ON c.owner = owner.id
WHERE
    owner.email IS NOT NULL
AND
    producer.email IS NOT NULL
AND
    owner.birth_date >= c.produce_year
AND 
    (SELECT COUNT(*) FROM car WHERE car.producer = c.producer) >= 10

答案 1 :(得分:0)

我将使用第一个producers上提到的条件,在INNER JOIN上使用预过滤器。

SELECT
    *
FROM
    car
INNER JOIN
        ( SELECT
              producer.*
          FROM
              producer
          INNER JOIN
              car ON car.producer = producer.id
          GROUP BY
              producer.id
          HAVING
              COUNT(*) >= 10 ) AS p ON p.id = car.producer
INNER JOIN
    owner ON car.owner = owner.id
WHERE
    owner.email IS NOT NULL
AND
    p.email IS NOT NULL
AND
    owner.birth_date >= car.produce_year

此外,对where子句的限制可以转换为joins以减少查询,如下所示:

SELECT
    *
FROM
    car
INNER JOIN
        ( SELECT
              producer.*
          FROM
              producer
          INNER JOIN
              car ON car.producer = producer.id
          GROUP BY
              producer.id
          HAVING
              COUNT(*) >= 10 ) AS p ON p.id = car.producer AND p.email IS NOT NULL
INNER JOIN
    owner ON owner.id = car.owner
          AND owner.email IS NOT NULL
          AND owner.birth_date >= car.producer_year