如何从带有JOIN的表中选择3个查询

时间:2014-02-27 09:04:56

标签: php mysql join

我的表结构是:

table1:

id      |    title    |    category    | body
--------+-------------+----------------+---------------
1       | blah blah   | 2              | blah blah blah
2       | blah blah   | 3              | blah blah blah
3       | blah blah   | 2              | blah blah blah
4       | blah blah   | 1              | blah blah blah

表2:

id      |   cid    |   type    |     link
--------+----------+-----------+--------------------
1       | 1        | c1        | http://........
1       | 2        | c1        | http://........
1       | 3        | c1        | http://........
1       | 4        | c1        | http://........
1       | 2        | c2        | http://........
1       | 3        | c2        | http://........
1       | 1        | c2        | http://........

现在我使用此代码在3个单独的查询中从这些表中进行选择:

$query = mysql_select("SELECT * FROM table1");
while ($result = mysql_fetch_array($query)) {
   $c1 = mysql_fetch_array(mysql_query("SELECT link FROM table2 WHERE cid=".$result['id']." AND type = 'c1' ORDER BY id DESC LIMIT 1"));
   $c2 = mysql_fetch_array(mysql_query("SELECT link FROM table2 WHERE cid=".$result['category']." AND type = 'c2' ORDER BY id DESC LIMIT 1"));

  ....
}

是否可以在mysql的一个查询中编写这些查询?

1 个答案:

答案 0 :(得分:0)

SELECT * FROM table1 a
LEFT JOIN table2 b ON b.cid = a.id AND type = 'c1'
LEFT JOIN table2 c ON b.cid = a.category AND type = 'c2'
ORDER BY a.title ASC, b.id DESC, c.id DESC

可能会使用ORDER BY进行扩展。

您也可以尝试使用INNER JOIN,如果您只想获取table1的行,table2中包含请求的行。