MySQL使用子查询中的表字段作为条件

时间:2013-03-18 10:20:10

标签: mysql subquery conditional-statements having

经过大量搜索后,我来到了以下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

兴趣点是子查询中具有名称LIKE的条件。如果我在那里写名字作为字符串(HAVING名称LIKE'%bmw%'),它可以工作,但我必须使用表a的名称字段来获得特定品牌的所有平均评级。有没有想法如何实现这一目标?感谢。

2 个答案:

答案 0 :(得分: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,'%'))

答案 1 :(得分: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