我有这些表
Currencies Table
Columns : curn_I'd, curn_name, curn_rate
Products Table
Columns : pro_I'd, pro_price, pro_currency -- Pro_currency in Products Table come from curn_id in the Currencies table
这种方式例如我有以下情况:
Product table's data as
Id Price Currency
1 100 2
2 200 5
3 300 1
4 400 5
5 500 4
这意味着我有许多不同价格和不同货币类型的产品。
如何搜索价格在200到400美元之间的产品。
在查询数据库然后搜索所有产品之前,我需要将所有价格转换成美元。
答案 0 :(得分:1)
以下SQL查询将通过挂钩货币来加入货币和产品表,并将产品ID列为各个货币的产品价格。
SELECT
p.id, p.pro_price * c.curn_rate, c.curn_id
FROM
products p, currencies c
WHERE
p.pro_currency = c.curn_id;
答案 1 :(得分:0)
我得到的答案是作为SQlserver考虑(我不了解MYSQl,你只是转换或思考这个查询的逻辑)
--create table
declare @currency table (id int, curn_name varchar(50) , curr_rate float )
declare @product table (id int, price float , currency int )
--insert data into table
insert into @currency values (1, 'Dollar', 67.22) , (2,'Euro' ,75.38 )
insert into @product values (1,100,2),(2,200,5), (3,300,1),(4,400,5), (5,500,4)
--select query to see data
select * from @currency
select * from @product
--This query gives you desired result
select p.Id, curn_name CurrencyName, curr_rate CurrentCurrencyRate, p.price ProductPrice, p.price * c.curr_rate DollarPrice
from @product p -- give always alies
JOIn @currency c on p.currency = c.id
Output Result
Id CurrencyName CurrentCurrencyRate ProductPrice DollarPrice
3 Dollar 67.22 300 20166
1 Euro 75.38 100 7538
答案 2 :(得分:0)
以下查询列出所有不同的产品及其价格(考虑货币汇率以美元计算):
SELECT
DISTINCT pro.id, pro.pro_price*cur.curn_rate AS price
FROM
products AS pro, currencies AS cur
WHERE
pro.pro_currency = cur.curn_id
AND
pro.pro_price * cur.curn_rate >= 200
AND
pro.pro_price * cur.curn_rate <=400
以ANSI格式查询:
SELECT
DISTINCT pro.Id, pro.pro_price*cur.curn_rate AS price
FROM
products AS pro
INNER JOIN
currencies AS cur
ON pro.pro_currency = cur.curn_Id
WHERE
pro.pro_price * cur.curn_rate >= 200
AND
pro.pro_price * cur.curn_rate <=400