我需要使用子查询来命名查询中的列。我在SELECT
部分编写了一个带子查询的语句,但是我收到以下错误消息(从Codeigniter返回):
错误号码:1064
您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以便在'(
ps_url_name
FROMproduct_selects
WHEREps_id
='1'),psc_opt_2
A'附近使用正确的语法在第1行
SELECT
`psc_opt_1` AS (SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '1'),
`psc_opt_2` AS (SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '2'),
`psc_opt_3` AS (SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '3'),
`psc_opt_4` AS (SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '4'),
`psc_opt_5` AS (SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '5')
FROM (`product_stock_control`)
WHERE `psc_prod_id` = '5'
文件名:models / products_model.php
行号:602
任何想法出了什么问题?
答案 0 :(得分:2)
AS
是一个列别名运算符,这意味着您要选择这些变量作为标识符。您不能使用运算符来识别带有查询的变量。
参考:http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html
相反,您需要反转如何使用别名运算符:
SELECT
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '1') AS `psc_opt_1`,
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '2') AS `psc_opt_2`,
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '3') AS `psc_opt_3`,
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '4') AS `psc_opt_4`,
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '5') AS `psc_opt_5`
FROM (`product_stock_control`)
WHERE `psc_prod_id` = '5'
理想情况下,您应该避免使用子查询(特别是在这种情况下)以避免表锁定开销。
答案 1 :(得分:0)
正确的格式是
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '1') As `psc_opt_1`
答案 2 :(得分:0)
你试过这个:
SELECT
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '1') as `psc_opt_1`,
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '2') as `psc_opt_2`,
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '3') as `psc_opt_3`,
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '4') as `psc_opt_4`,
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '5') as `psc_opt_5`
FROM (`product_stock_control`)
WHERE `psc_prod_id` = '5'
答案 3 :(得分:0)
您是否要将此列命名为psc_opt_1到psc_opt_1,或者您想要什么?
命名就像这样:
SELECT
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '1') AS `psc_opt_1`,
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '2') AS `psc_opt_2`,
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '3') AS `psc_opt_3`,
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '4') AS `psc_opt_4`,
(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '5') AS `psc_opt_5`
FROM (`product_stock_control`)
WHERE `psc_prod_id` = '5'