我的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。
答案 0 :(得分:1)
你遇到的问题是,当你说一个select时,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.
答案 1 :(得分: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