以下行给出了错误消息。
$query = 'SELECT * FROM products AS p LEFT JOIN categories AS c USING ON c.id = p.category_id WHERE c.name = "Galleri1"
AND p.status = "active"' ;
$Q = $this->db->query($query);
数据库结构。 类别
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`shortdesc` varchar(255) NOT NULL,
`longdesc` text NOT NULL,
`status` enum('active','inactive') NOT NULL,
`parentid` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
...
...
产品
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`shortdesc` varchar(255) NOT NULL,
`longdesc` text NOT NULL,
`thumbnail` varchar(255) NOT NULL,
`image` varchar(255) NOT NULL,
`class` varchar(255) DEFAULT NULL,
`grouping` varchar(16) DEFAULT NULL,
`status` enum('active','inactive') NOT NULL,
`category_id` int(11) NOT NULL,
`featured` enum('true','false') NOT NULL,
`price` float(4,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ;
错误消息
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ON c.id = p.category_id WHERE c.name = "Galleri1" AND p.status = "active"' at line 1
SELECT * FROM products AS p LEFT JOIN categories AS c USING ON c.id = p.category_id WHERE c.name = "Galleri1" AND p.status = "active"
Q1。任何人都可以指出我的错误吗?
Q2。谁能告诉我如何在Codeigniter的Active Record课程中写这个?
提前致谢。
答案 0 :(得分:2)
使用单引号,摆脱USING
并使JOIN
内部:
SELECT *
FROM products AS p
JOIN categories AS c
ON c.id = p.category_id
WHERE c.name = 'Galleri1'
AND p.status = 'active'
双引号用于标记用作表名和列名的保留字。字符串文字应括在单引号中。
JOIN USING (col1)
表示您在两个表中都有一个名为col1
的字段,并希望加入该字段。如果不这样做,则应使用JOIN ON
将此条件c.name = 'Galleri1'
置于WHERE
子句中会使LEFT JOIN
返回与INNER JOIN
完全相同的记录。后者更有效(因为优化器可以选择在连接中引导哪个表)。
答案 1 :(得分:0)
USING
和ON
是两种不同的方式来确定与哪些列进行连接。您的查询指定了两者,但看起来您尝试使用ON
语法。请尝试以下方法:
SELECT * FROM products AS p LEFT JOIN categories AS c ON c.id = p.category_id WHERE c.name = "Galleri1"