2013-04-09 97 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);"