首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MySQL查询,codeigniter中的子查询

MySQL查询,codeigniter中的子查询
EN

Stack Overflow用户
提问于 2013-03-13 04:54:16
回答 2查看 384关注 0票数 0

我正在使用codeigniter作为我的框架,但是我没有使用活动记录,我在执行这个查询时遇到了问题,它给出了一个错误号1064

本质上,我试图将一堆数据插入到一个表中,但是从其他表中查询了一些id号。

代码语言:javascript
复制
$titulo = $datos['titulo'];
    $tipo   =   $datos['tipo'];
    $autor  =   $datos['autor'];
    $autor2 =   $datos['autor2'];
    $editorial =    $datos['editorial'];
    $ano        =   $datos['ano'];
    $paginas    =   $datos['paginas'];
    $descripcion =  $datos['descripcion'];
    $image_path =   'hola';
    $genero     =   $datos['genero'];
    $genero2    =   $datos['genero2'];


    $sql = "INSERT INTO productos (titulo, autor_id, autor2_id, editorial_id, ano, paginas, genero_id,
             genero2_id, tipo, descripcion, image_path)
             SELECT ? AS titulo,
             id FROM autores WHERE nombre_autor=?,
             id FROM autores WHERE nombre_autor=?,
             id FROM editoriales WHERE nombre_editorial=?,
             ? as ano, 
             ? as paginas,
             id FROM generos WHERE nombre_genero=?,
             id FROM generos WHERE nombre_genero=?,
             ? as tipo,
             ? as descripcion,
             ? as image_path";

    if($this->db->query($sql, array($titulo, $autor, $autor2, $editorial, $ano, $paginas, $genero, $genero2, $tipo, $descripcion, $image_path))){
        return true;
    }else{
        return false;
    }  

有人能帮我解决这个问题吗?

谢谢..。

EN

回答 2

Stack Overflow用户

发布于 2013-03-13 05:18:50

一个select语句只能有一个FROM子句。

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

了解使用JOIN

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

票数 0
EN

Stack Overflow用户

发布于 2013-03-13 05:47:00

这不是一个完美的查询,因为我不知道您的数据库的设计,但它应该引导您在语法方面的正确方向。

代码语言:javascript
复制
INSERT INTO productos (titulo, autor_id, autor2_id, editorial_id, ano, paginas, genero_id,
         genero2_id, tipo, descripcion, image_path)
SELECT a.titulo, b.id, b.id2, c.id, a.ano, a.paginas, d.id, d.id2, a.tipo, a.description, a.image_path
FROM table_1 a
JOIN table_2 b ON a.autor_id = b.id
JOIN table_3 c ON a.editorial_id = c.id
JOIN table_4 d ON a.genero_id = d.id
WHERE a.id = 25

本质上,这将把你需要的所有数据连接到一个表中,然后再添加到"productos“中。这是使用SQL执行所需操作的正确方法。当然,这还取决于表之间的关系--在本例中,我假设table_1中有引用其他表中数据的外键。

然后,您将能够根据您想要/需要的任何参数执行此查询--只需参考WHERE子句中的那些参数。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15371931

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档