按条件在另一个表中选择产品

时间:2014-06-03 07:39:57

标签: php mysql

我使用joomla joomshopping组件,现在我遇到了一个复杂的问题。我需要从数据库中选择产品,这些产品属于extra_field条件范围内的imean。

我们有两张桌子

jshopping_products

product_id | product_name | extra_field_1 | extra_field_2
1          | my_product   | 1             | 2
2          | my_product2  | 1             | 3 
3          | my_product3  | 4             | 3

extra_field_values

id         | field_id     | name          
1          | 1            | 100
2          | 2            | 200
3          | 2            | 300 
4          | 1            | 150

我想选择100-120范围内的所有产品extra_field_1和200-205 for extra_field_2所以结果应该是第一个产品

我尝试的sql看起来像这样

$sql = mysql_query("SELECT a.* FROM jshopping_products a, jshopping_products_extra_field_values b WHERE (b.name >= 100 AND b.name <= 120 AND there is a problem ");

我如何配对这两张桌子?

已编辑 *******

$query = "
SELECT  
  ".$prefix."jshopping_products.* 
FROM
  ".$prefix."jshopping_products
   JOIN ".$prefix."jshopping_products_extra_field_values field_2 ON ".$prefix."jshopping_products.extra_field_2 = field_2.id
   JOIN ".$prefix."jshopping_products_extra_field_values field_7 ON ".$prefix."jshopping_products.extra_field_7 = field_7.id
   JOIN ".$prefix."jshopping_products_extra_field_values field_8 ON ".$prefix."jshopping_products.extra_field_8 = field_8.id
   JOIN ".$prefix."jshopping_products_extra_field_values field_9 ON ".$prefix."jshopping_products.extra_field_9 = field_9.id
   JOIN ".$prefix."jshopping_products_extra_field_values field_10 ON ".$prefix."jshopping_products.extra_field_10 = field_10.id
   JOIN ".$prefix."jshopping_products_extra_field_values field_11 ON ".$prefix."jshopping_products.extra_field_11 = field_11.id
   JOIN ".$prefix."jshopping_products_extra_field_values field_12 ON ".$prefix."jshopping_products.extra_field_12 = field_12.id
   JOIN ".$prefix."jshopping_products_extra_field_values field_13 ON ".$prefix."jshopping_products.extra_field_13 = field_13.id
WHERE
  field_10.`name_cs-CZ` BETWEEN 0 and 999999999
";

感谢响应,我设法做到这一点,无论如何它只给我一个产品,我确实在extra_field_10中有大约100个值,范围为60-10000,超过200个产品

2 个答案:

答案 0 :(得分:1)

SELECT distinct jshopping_products.*
FROM   jshopping_products
   JOIN extra_field_values field_1 ON jshopping_products.extra_field_1 = field_1.id
   JOIN extra_field_values field_2 on jshopping_products.extra_field_2 = field_2.id
WHERE
    field_1.name BETWEEN 100 AND 120 AND
    field_2.name BETWEEN 200 AND 205

答案 1 :(得分:0)

您必须两次加入extra_field_values表,一次加入jshopping_products中与您一起加入的每个列

SELECT a.*
FROM jshopping_products a
JOIN jshopping_products_extra_field_values e1 ON a.extra_field_1 = e1.id
JOIN jshopping_products_extra_field_values e2 ON a.extra_field_2 = e2.id
WHERE e1.name BETWEEN 100 AND 120
AND e2.name BETWEEN 200 AND 205
GROUP BY a.product_id