比较2个表时,无法返回正确的结果

时间:2014-03-14 13:29:12

标签: php mysql

我有两张这样的表:

产品

<table>
    <tr>
        <th>id</th>
        <th>name</th>
        <th>description</th>
    </tr>
    <tr>
        <td>1</td>
        <td>book</td>
        <td>book desc</td>
    </tr>
    <tr>
        <td>2</td>
        <td>tea</td>
        <td>tea desc</td>
    </tr>
    <tr>
        <td>3</td>
        <td>glasses</td>
        <td>glasses desc</td>
    </tr>
</table>

product_attributes

<table>
    <tr>
        <th>product_id</th>
        <th>attribute_id</th>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
    <tr>
        <td>2</td>
        <td>7</td>
    </tr>
    <tr>
        <td>2</td>
        <td>8</td>
    </tr>
    <tr>
        <td>3</td>
        <td>2</td>
    </tr>
    <tr>
        <td>3</td>
        <td>7</td>
    </tr>
    <tr>
        <td>3</td>
        <td>9</td>
    </tr>
    <tr>
        <td>3</td>
        <td>10</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
    <tr>
        <td>1</td>
        <td>5</td>
    </tr>
    <tr>
        <td>1</td>
        <td>7</td>
    </tr>
</table>

我还有两个变量(字符串),$pid$search_ids

$pid包含产品ID,其值为2,3,1 $search_ids包含属性ID,值为7,8

我想从name表返回productsproduct_attributes表中的product_id attribute_id$pid中的$search_ids包含来自{{1}的值}和TEA

因此,对于上面指定的表,我希望只返回$search_ids,因为只有它的id匹配product_attributes表中$q = "SELECT p.name FROM products AS p, product_attributes AS pa WHERE p.id IN ($pid) AND pa.product_id IN ($pid) AND pa.attribute_id IN ($search_ids)"; 的两个ID。

我尝试了以下操作,但由于某种原因,这会返回我有四次的所有产品:

{{1}}

1 个答案:

答案 0 :(得分:0)

尝试此更改

SELECT  p.name 
FROM products AS p, product_attributes AS pa 
WHERE p.id = pa.product_id  <---!!!
AND p.id IN ($pid) AND pa.attribute_id IN ($search_ids)

您需要指定加入。