Mysql定义要由其他表中的子内部查询选择的列名

时间:2014-10-27 17:43:48

标签: php mysql database syntax-error

我有这样的表1

weight pr_1 pr_2 pr_3 pr_4 pr_5 pr_6 pr_7 pr_8 pr_9
5 41.47 49.06 54.63 49.42 45.24 54.63 45.52 30.7 44.57
6 43.19 51.73 58.81 53.87 46.1 58.81 46.39 31.56 45.43

和表2一样

country_name price_range
canada pr_1
united_kingdom pr_2
europe pr_3
australia pr_4
japan pr_5
europe_o pr_6
middle_east_africa pr_7
asia pr_8
latin_america pr_9

我正在尝试运行一个select查询,该查询将从表1中获取数据,获取列名以从子查询中获取数据

SELECT IN(SELECT `price_range` FROM `ps_parcel_connect_countries` WHERE `country_name`  LIKE  'canada' ) as `price_range` FROM `ps_parcel_connect_weight_ranges` WHERE `weight`<=5

但是当我在phpmyadmin中运行它时会给我错误

#1064 - 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 'IN(SELECT `price_range` FROM `ps_parcel_connect_countries` WHERE `country_name` ' at line 1

在第-1行看不到任何错误很奇怪。

如果有人能指出我正确的方向,将会非常有帮助

由于

1 个答案:

答案 0 :(得分:0)

这里你应该至少有3张桌子。一个包含您的国家/地区数据的

country
-------
country_id [autoincrement]
country_name [index]

使用示例数据:

country_id   country_name
----------   ------------
1            Canada
2            United Kingdom
...
9            Latin America

一个有你体重渐变的人

weight
------
weight_id [automincrment]
weight_value [index]

使用示例数据:

weight_id   weight
---------   ------
1           5
2           6

将国家和权重与价格联系起来

price_by_country_and_weight
--------
price_id [autoincrement]
country_id 
weight_id [unique index across country_id and weight_id]
price

使用以下示例数据:

price_id    country_id    weight_id   price
--------    ----------    ---------   -----
1           1             1           41.47
2           2             1           49.06
3           3             1           54.63
...
10          1             2           43.19
11          2             2           51.73
...
18          9             2           45.43

然后你会这样查询:

SELECT p.price
FROM country AS c
INNER JOIN price_by_country_and_weight AS p
    ON c.country_id = p.country_id
INNER JOIN weight AS w
    ON p.weight_id = w.weight_id
WHERE
    c.country_name = 'Canada'
    AND w.weight <= 5
ORDER BY w.weight ASC