2013-04-09 128 views
0
company     company_to_attributes 
=====================  ============================ 
| id_company | name  id_attributes | id_company 
=====================  ============================ 
| 1   | Test  | 1   | 1    
| 2   | Test 2  | 2   | 1    
| 3   | Test 3  | 3   | 1   
| 4   | Test 4  | 4   | 3 
| ..   | ...   | ..   | ... 
=====================  ============================ 

我有一个简单的数组:MySQL查询数组参数

$array_attributes_IDS = array(1,2); 

我想要写的获取有id_attribute从阵列公司查询。因为同时包含属性

+0

请出示什么结果应该是你想要做什么的一些例子。 – 2013-04-09 09:29:46

回答

2

试试这个,

$array_attributes_IDS = array(1,2); 
$finalArray = implode(',', $array_attributes_IDS); 
$arrCount = count($array_attributes_IDS); 

$query =" SELECT com.name 
      FROM company com 
      INNER JOIN company_to_attributes att 
       ON com.id_company = att.id_company 
      WHERE att.id_attributes IN ($finalArray) 
      GROUP BY com.name 
      HAVING COUNT(*) = $arrCount"; 

这将返回只有一家公司TEST

+0

Thk回复。查询工作正常,但我的数组是不动的,我没有多少元素包含。如何解决查询COUNT? – Mike 2013-04-09 09:42:27

+0

看到我更新的答案。 – 2013-04-09 09:49:05

+0

它是完美的!非常感谢你。 – Mike 2013-04-09 09:51:28

0
SELECT c.* FROM company c INNER JOIN company_to_attributes ca ON c.id_company=ca.id_company WHERE ca.id_attributes IN (1,2) 
0

,请尝试以下方法:

$array_attributes_IDS = array(1,2); 
    $finalArray = implode(',', $array_attributes_IDS); 
    $query = "SELECT C.name FROM company_to_attributes CA INNER JOIN company C ON CA.id_company = C.id_company WHERE CA.id_attributes IN ($finalArray)"; 

希望这会有所帮助。

+0

Thk为答案。我会选择所有具有所有array_attributes_IDS值的公司。如果具有所有价值。 – Mike 2013-04-09 09:40:24

+0

@Mike:使用INNER JOIN,您将获得与至少1个属性关联的所有公司。我希望这是你想要的。还是你想要所有的共同点,即使它不与任何属性相关联?请解释 – 2013-04-09 09:44:24

0
SELECT c.name 
FROM company c 
     JOIN company_to_attributes a 
      ON c.id_company = a.id_company 
WHERE a.id_attributes IN (1,2) 
0
$sql = " 
SELECT t1.name FROM company_to_attributes 
LEFT JOIN company AS t1 ON t1.id_company = company_to_attributes.id_company 
WHERE company_to_attributes.id_attributes IN (".implode(',', $array_attributes_IDS).") 
"; 
0
"SELECT c.name from company c inner join company_to_attributes cta ON cta.id_company = c.id_company WHERE cta.id_attributes IN (1,2);"