【问题标题】:How to select from table with JOIN instead 3 queries如何使用 JOIN 代替 3 个查询从表中进行选择
【发布时间】:2014-02-27 09:04:56
【问题描述】:

我的表结构是:

表1:

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 查询中编写这些查询?

【问题讨论】:

  • 第二次查询:WHERE cid=".$result['id']。第三个查询:WHERE cid=".$result['category']。你确定吗?
  • 是的,这是我的问题,我在一张表中有两种类型的记录

标签: php mysql join


【解决方案1】:
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扩展。

如果您只想获取table1 的那些行,您也可以尝试INNER JOIN,这些行在table2 中有请求的行。

【讨论】:

  • 您没有从 table2 中选择 link。
  • 谢谢,我使用ORDER 因为可能我们在table2 中有多个记录,所以我通过id 订购以选择最新记录,我该如何在此查询中执行此操作?
  • @Theox 我使用SELECT *,它只选择所有内容。
  • @MajAfy 您还必须决定如何对 table1 进行排序,因为您必须先排序,然后再排序。那么表 1 的首选顺序是什么?
猜你喜欢
  • 2014-09-17
  • 1970-01-01
  • 2019-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-26
  • 1970-01-01
  • 2015-03-21
相关资源
最近更新 更多