0

我对 MySQL 语句有疑问。

我有这个:

SELECT ad.*, 
  (SELECT img.image 
   FROM '.$this->config->db_prefix.'_images AS img 
   WHERE img.aid = ad.aid LIMIT 1) AS img 
FROM '.$this->config->db_prefix.'_adverts ad 
WHERE fid = :fid 
ORDER BY cr_date DESC

哪个工作正常,但我需要从_images表中获取所有图像,所以如果我删除LIMIT 1我得到

Cardinality violation: 1242 Subquery returns more than 1 row

SQL 的结果以 JSON 格式输出。

4

2 回答 2

1

您遇到的问题是,当您说选择时,mysql 希望一次获得一个条目。看一下mysql JOIN 语句。

http://dev.mysql.com/doc/refman/5.0/en/join.html

select ad.*, img.image 
from TABLE1 ad 
JOIN TABLE2 img on ad.aid = img.aid 
WHERE CONDITION 
ORDER BY cr_date DESC.
于 2013-09-22T16:13:09.830 回答
1

您可能会使用GROUP_CONCAT()MySQL 聚合函数:

SELECT ad.*, (SELECT GROUP_CONCAT(img.image) FROM '.$this->config->db_prefix.'_images AS img WHERE img.aid = ad.aid) AS img FROM '.$this->config->db_prefix.'_adverts ad WHERE fid = :fid ORDER BY cr_date DESC

然后explode()它在 php 中或split()稍后在 javascript 中。

于 2013-09-22T16:13:22.043 回答