因为 , 的数据car_accidents
位于violations
单独的表中,所以您需要使用left join
.
希望这是有道理的:-)
SELECT Count(*),
Avg(sl.our_cost),
Avg(sl.purchase_price)
FROM sold_leads AS sl
INNER JOIN leads AS l
ON l.id = sl.lead_id
INNER JOIN contacts AS c
ON c.lead_id = l.id
INNER JOIN drivers AS d
ON d.lead_id = l.id
LEFT JOIN
(SELECT ca1.driver_id, COUNT(*) AS cnt FROM car_accidents ca1 GROUP BY ca1.driver_id) ca
ON (c.state = 'CA' and ca.driver_id = d.id)
LEFT JOIN
(SELECT v1.driver_id, COUNT(*) AS cnt FROM violations v1 GROUP BY v1.driver_id) v
ON (c.state IN ('CA') and v.driver_id = d.id)
WHERE c.state IN( 'AK', 'AL', 'AR', 'AZ','CA', 'CO', 'CT', 'DC',
'DE', 'FL', 'GA', 'HI','IA', 'ID', 'IL', 'IN',
'KS', 'KY', 'LA', 'MD','ME', 'MI', 'MN', 'MO',
'MS', 'MT', 'NC', 'ND','NE', 'NH', 'NJ', 'NM',
'NV', 'NY', 'OH', 'OK','OR', 'PA', 'RI', 'SC',
'SD', 'TN', 'TX', 'UT','VA', 'VT', 'WA', 'WI',
'WV', 'WY' )
AND l.leg = 0
AND ( Datediff(CURRENT_DATE, d.date_of_birth) / 365 ) >= 50
AND l.create_date >= '2012-1-1'
AND IFNULL(v.cnt,0) < 2 AND ifnull(ca.cnt.0) < 2
AND (c.state IN ('FL','MD','NH','WA') OR c.IsInsured = 1)
note
将状态放在单独的表中会更有意义。这样,您可以将条款和条件放在该表中,并在您的联接条件中使用它们。
Table state
-----------
id : varchar(2) primary key not null
country : varchar(45) not null
max_accidents : int null
max_violations : int null
must_be_insured : boolean not null
然后您可以将查询重写为:
SELECT Count(*),
Avg(sl.our_cost),
Avg(sl.purchase_price)
FROM sold_leads AS sl
INNER JOIN leads AS l
ON l.id = sl.lead_id
INNER JOIN contacts AS c
ON c.lead_id = l.id
INNER JOIN drivers AS d
ON d.lead_id = l.id
INNER JOIN state s ON (s.id = c.state)
LEFT JOIN
(SELECT ca1.driver_id, COUNT(*) AS cnt FROM car_accidents ca1 GROUP BY ca1.driver_id) ca
ON (s.max_accidents IS NOT NULL AND ca.driver_id = d.id)
LEFT JOIN
(SELECT v1.driver_id, COUNT(*) AS cnt FROM violations v1 GROUP BY v1.driver_id) v
ON (s.max_violations IS NOT NULL AND v.driver_id = d.id)
AND l.leg = 0
AND (Datediff(CURRENT_DATE, d.date_of_birth) / 365.25 ) >= 50
AND l.create_date >= '2012-1-1';
AND IFNULL(v.cnt,0) < 2 AND ifnull(ca.cnt.0) < 2
AND (s.must_be_insured = 0 OR c.IsInsured = 1)