1

经过大量搜索后,我得出以下 sql 语句:

SELECT a.*, b.name as producer ,
    (SELECT ROUND(AVG(average)) 
    FROM `abc123_pb_carexperience` d 
    LEFT JOIN `abc123_pb_cars` e on d.car_id=e.id HAVING name LIKE '%a.name%') as avgrating
FROM abc123_pb_brands a
LEFT JOIN abc123_pb_producer as b on a.producer_id = b.id
ORDER BY a.name ASC

兴趣点是子查询中的条件 HAVING name LIKE。如果我将名称写为字符串(HAVING name LIKE '%bmw%'),它可以工作,但我必须使用表 a 的名称字段来获取特定品牌的所有平均评级。有没有办法做到这一点?谢谢。

4

2 回答 2

2

我认为您的内部子查询应如下所示:

  (SELECT ROUND(AVG(average)) 
    FROM `abc123_pb_carexperience` d 
    LEFT JOIN `abc123_pb_cars` e on d.car_id=e.id 
    WHERE name LIKE CONCAT('%',a.name,'%'))
于 2013-03-18T10:29:28.980 回答
0

您可以像这样更改您的查询

SELECT
  a.*,
  b.name as producer,
  ROUND(AVG(d.average)) as avgrating
FROM abc123_pb_brands a
  LEFT JOIN abc123_pb_producer as b
    on a.producer_id = b.id
  LEFT JOIN `abc123_pb_carexperience` d
    ON d.name LIKE '%a.name%'
  LEFT JOIN `abc123_pb_cars` e
    on d.car_id = e.id
ORDER BY a.name ASC
于 2013-03-18T10:31:15.417 回答