0

我需要使用子查询来命名查询中的列。我在该SELECT部分中编写了带有子查询的语句,但收到以下错误消息(从 Codeigniter 返回):

错误号:1064

您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 '(SELECT ps_url_nameFROM product_selectsWHERE ps_id= '1'), psc_opt_2A'附近使用正确的语法

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

任何想法出了什么问题?

4

4 回答 4

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'

理想情况下,您应该避免使用子查询(尤其是在这种情况下)以避免表锁定开销。

于 2012-08-09T16:57:18.283 回答
0

正确的格式是

(SELECT `ps_url_name` FROM `product_selects` WHERE `ps_id` = '1') As `psc_opt_1` 
于 2012-08-09T16:58:20.463 回答
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'
于 2012-08-09T16:59:01.450 回答
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'
于 2012-08-09T17:03:08.093 回答