MySQL查询,添加新别名

时间:2014-08-18 12:17:43

标签: php mysql

我有一个mysql查询用于搜索脚本,我需要添加另一个字段(如SPV.term别名)这段代码告诉我一个错误号码:1054未知栏' S.id'在条款'。

$query = "
SELECT
  SP.url,
  SP.id,
  S.name,
  SP.hit,
  SP.hot,
  SP.action,
  SP.id,
  SP.smallimage,
  SP.mainmodimage,
  (SELECT
     stock
   FROM shop_product_variants
   WHERE shop_product_variants.product_id = S.id
       AND stock > 0
   LIMIT 1) as stock,
  (SELECT
     price
   FROM shop_product_variants
   WHERE shop_product_variants.product_id = S.id
    OR shop_product_variants.product_id = S.id
       AND stock = 0
   LIMIT 1) as price,
  (SELECT
     id
   FROM shop_product_variants
   WHERE shop_product_variants.product_id = S.id
    OR shop_product_variants.product_id = S.id
       AND stock = 0
   LIMIT 1) as v_id,
  (SELECT
     old_price
   FROM shop_product_variants
   WHERE shop_product_variants.product_id = S.id
       AND stock > 0
   LIMIT 1) as old_price
FROM shop_products_i18n S,
  shop_product_variants SPV
  INNER JOIN shop_products SP
    ON SP.id = S.id
WHERE SP.active = 1
    AND S.name LIKE '%" . $get . "%'
     OR SP.url LIKE '%" . $get . "%'
     OR SPV.term LIKE '%" . $get . "%'
GROUP BY S.id
ORDER BY stock DESC
";

1 个答案:

答案 0 :(得分:1)

这是您的from条款:

FROM shop_products_i18n S,
     shop_product_variants SPV INNER JOIN
     shop_products SP
     ON SP.id = S.id

问题在于您正在混合旧式连接和新式连接。一个简单的规则:永远不要在from子句中使用逗号。

我认为你的意思是:

FROM shop_products_i18n S INNER JOIN
     shop_products SP
     ON SP.id = S.id

因为除了SPV子句外,您不在外部查询中的任何其他地方使用where。这种情况可能会进入每个子查询。

顺便说一句,您可以将,替换为cross join来解决原始问题:

FROM shop_products_i18n S CROSS JOIN
     shop_product_variants SPV INNER JOIN
     shop_products SP
     ON SP.id = S.id

虽然,cross join都执行笛卡尔积,但在优先级方面,它们在FROM子句中的行为却不同。您对,的问题在于优先规则首先解析了以下INNER JOIN - 因此S中的列不可用。