MySQL:将id转换为值

时间:2011-12-14 22:52:44

标签: mysql sql database

我有一个表,其中包含很多列,其中id(键)对应于其他表。 例如,我有一张已售出的汽车表

[table of cars that were sold]
(
  car_make_id
, car_engine_id
, car_model_id
, car_radio_id
, buyer_id
, seller_id
, car_tittle_id
, sale_price
)

每个id字段都有另一个包含id和名称的表,如:

[another table]
(
  car_make_id
, car_engine_id
, car_model_id
, car_radio_id
, buyer_id
, seller_id
, car_tittle_id
, sale_price
)

[and another table]
(
  car_make
, car_make_id
)

[and another table]
(
  car_title
, car_title_id
)

等,...每个表名为car_lookupcar_model_lookup,...

无论如何加入所有这些只是没有写一百万个子查询。此表中有数百万个条目,每个额外的连接在时间上都有很多。我正在寻找一种快速有效的方法来比较这些数据与另一个没有id的表,而只是名称。假设我有一个兼容的无线电列表(制造商,型号,引擎,无线电),我希望列出所有销售具有不兼容无线电的汽车的卖家名单,以及他们制作了多少不兼容的销售。

我在perl中一直在做这样的事情,但可能需要几个小时才能运行。所以我正在寻找可以在mysql中完成的事情。

ps:汽车的东西只是一个例子,我实际上并没有使用汽车,但它说明了我遇到的问题。由于已经查询数据的大量代码,我无法更改数据库的设置方式。

由于

1 个答案:

答案 0 :(得分:0)

您需要一些方式告诉数据库哪些表从每个ID中提取名称。

如果这种查询太慢,也许您可​​以优化数据库或MySQL服务器,以便能够更快地填充这些JOIN语句。尝试增加缓存大小(特别是如果您的服务器有大量RAM)并确保在这些查找表上有密钥索引。

SELECT car_make, car_engine, car_model, car_radio,
       buyer, seller, car_title, sale_price FROM cars_sold
JOIN car_make_lookup USING (car_make_id)
JOIN car_engine_lookup USING (car_engine_id)
JOIN car_title_lookup USING (car_title_id)
JOIN car_model_lookup USING (car_model_id)
JOIN car_radio_lookup USING (car_radio_id)
JOIN buyer_lookup USING (buyer_id)
JOIN seller_lookup USING (seller_id)
JOIN car_title_lookup USING (car_title_id)