mysql查询数组参数

时间:2013-04-09 09:27:09

标签: php mysql

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
| ..         | ...         | ..          | ... 
=====================      ============================

我有一个简单的数组:

$array_attributes_IDS = array(1,2);

我想编写一个查询,以便从数组中获取具有id_attribute的公司。

6 个答案:

答案 0 :(得分: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,因为它包含两个属性。

答案 1 :(得分: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)

答案 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)";

希望这会有所帮助。

答案 3 :(得分: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)

答案 4 :(得分: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).")
";

答案 5 :(得分: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);"