开发者

In PHP, how do I query a mySQL database using multiple "IN" statements across different tables?

I am trying to figure out how to have two "IN" statements.

I'm trying to get something like this, although I don't know how to use both of the nested select statements.

$query_row=mysql_query(
    "SELECT DISTINCT * FROM table_a WHERE field_1 IN 
        (SELECT field_1 FROM table_b WHERE field_2 = $field_2), 
        (SELECT field_3 FROM table_c WHERE field_4 = $fi开发者_StackOverflow中文版eld_4)
        ORDER BY field_5 DESC
        ");

If I remove one of the (SELECT... bits, it works, but trying to put them both does not.

Table a has matching values in tables B and C: fields 2 and 4 respectively.

How do I get this to work?


Depending if you want to test if IN either or both:

WHERE field_1 IN (SELECT field_1 FROM table_b WHERE field_2 = $field_2) AND/OR field_1 IN (SELECT field_3 FROM table_c WHERE field_4 = $field_4) ...


You could try it with a UNION:

SELECT DISTINCT * 
    FROM table_a 
    WHERE field_1 IN (SELECT field_1 FROM table_b WHERE field_2 = $field_2 
                      UNION 
                      SELECT field_3 FROM table_c WHERE field_4 = $field_4)
    ORDER BY field_5 DESC
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜