我有两张这样的表:
帖子表:
post_id subject
1 abc
2 def
和内容表,其中post_id
列是外键:
content_id post_id content date
1 1 main content 2014-07-31 03:02:00
2 1 reply one 2014-07-31 03:03:20
3 1 reply two 2014-07-31 03:06:32
如您所见,内容表存储了帖子的内容及其可能的复制内容。在此示例中,post_id
#1有其主要内容和两个回复。
我想要做的是回显主题及其内容,但不是回复。所以我编写了这样的查询:
$query = "SELECT subject, content
FROM posts As p
INNER JOIN contents AS c USING (post_id)
ORDER BY post_id DESC";
$result = mysqli_query ($dbc, $query)
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "{$row['content']}n\";
}
然后你知道吗?它回应了帖子的最新内容,即content_id
#3。但是,我想要做的是回应帖子的内容,这是最早的content_id
post_id
#1。
请帮帮我吗?
答案 0 :(得分:1)
MIN(DATE)
必须满足要求,因此您需要将id
与DATE
在post_id
的基础上加入两个表格,然后根据min(date)
$query = "SELECT p.post_id, p.subject, c.content, c.date
FROM posts p
INNER JOIN contents c on p.post_id = c.post_id
WHERE date = (select min(date)
from contents ct
where ct.post_id = p.post_id
)
GROUP BY post_id,subject,content, date
ORDER BY post_id DESC";
$result = mysqli_query ($dbc, $query)
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo "{$row['content']}n\";
}
答案 1 :(得分:1)
<强>已更新强>
它基本上选择子查询中每个帖子的最小日期,并将其用作“正常”查询的关键字。
SELECT distinct subject, content FROM content c
JOIN post p
on c.post_id = p.post_id
WHERE cast(c.post_id as char)+cast(c.contentdate as char)in
(
SELECT
cast(p.post_id as char)+cast(min(c.contentdate) as char) as KeyValue
FROM post p
INNER JOIN content c on p.post_id = c.post_id
GROUP BY p.post_id
)
这让我回报:
subject | content
----------------------
asd | main content
def | main content
答案 2 :(得分:0)
您还需要按content_id(或日期)订购结果。所以sql查询可能如下所示:
$query = "SELECT subject, content
FROM posts As p
INNER JOIN contents AS c USING (post_id)
ORDER BY post_id DESC, content_id ASC";
当然,我假设主要内容已在回复之前添加到数据库中,并且您不会更改行索引,这可能导致第一行具有某些post_id的情况不是实际内容。
因此,如果您想打印出代码中需要执行某些操作的所有内容。您只需要打印具有相同post_id的第一行:
$last_post_id = 0;
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
if ($last_post_id != $row['post_id']) {
echo "{$row['content']}n\";
}
$last_post_id = $row['post_id'];
}
答案 3 :(得分:0)
试试这个
$query = "SELECT subject, content
FROM posts As p
INNER JOIN contents AS c USING (post_id)
ORDER BY date ASC, post_id DESC";
答案 4 :(得分:0)
在测试了所有答案之后,我选择了 @NoobEditor 的答案。但是,我必须更清楚地说明如下:
$query = "SELECT p.post_id, p.subject, c.content, c.date
FROM posts p
INNER JOIN contents c on p.post_id = c.post_id
WHERE date = (select min(date)
from contents c
where c.post_id = p.post_id
)
GROUP BY c.post_id
ORDER BY p.post_id DESC";
$result = mysqli_query ($dbc, $query)
我在GROUP
和ORDER BY
函数中更清楚了。并使用 c 作为内容表的别名,但不需要使用 c 和 ct
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo "{$row['content']}n\";
}