我希望获得max id2值的所有id。 我试着获得最大id2但是它会在表格中查找id2的整体最大值,但我想获得所有最大值的id。
所以我得到了2个表 - 表新闻和表格主题。 每当我创建新闻时,都会自动创建一个主题。现在我想显示所有新闻 - 以及当前的回复数量。所以第一步 - topicid = id。
每个主题都有id和id2。
id是主题ID 和id2是回复ID
所以,如果我有4个评论的主题(a),它看起来像
(id(1),id2(1))
(id(1),id2(2))
(id(1),id2(3))
(id(1),id2(4))
现在是一个新主题(b),有6条评论
(id(2),id2(1))
(id(2),id2(2))
(id(2),id2(3))
(id(2),id2(4))
(id(2),id2(5))
(id(2),id2(6))
所以我想得到((id(1),id2(4))和(id(2),id2(6)))
<?php
$news = "SELECT n.titel,n.datum,n.typ_news,n.news,n.verfasser,n.time,n.topicid,
t.id, t.id2 FROM news n LEFT JOIN topics t ON t.id = n.topicid
ORDER BY n.id DESC LIMIT 10 ";
$neuenews = mysql_query($news);
while ($dnews = mysql_fetch_array($neuenews))
{
echo " <div style='text-align:center;color:#FFFFFF;font-size: 24px;'> "
.$dnews['titel'].
"a";
}
这是解决方案:
$dn1 = mysql_query('select c.id, c.name, c.description, c.position,c.bild,
(select count(t.id) from topics as t where t.parent=c.id and t.id2=1) as topics,
(select count(t2.id) from topics as t2 where t2.parent=c.id and t2.id2!=1) as replies
from categories as c group by c.id order by c.position asc');
答案 0 :(得分:0)
试试这个:
SELECT n.titel,n.datum,n.typ_news,n.news,n.verfasser,n.time,n.topicid, t.id, MAX(t.id2) AS id2
FROM news n
LEFT JOIN
topics t
ON t.id = n.topicid
GROUP BY n.topicid
ORDER BY n.id DESC LIMIT 10
答案 1 :(得分:0)
看起来topics
表中的指定/期望结果是通过如下查询完成的:
SELECT t.id
, MAX(t.id2) AS max_id2
FROM topics t
GROUP BY t.id
选项1
要将结果连接到news
中的行,您可以将该查询用作查询中的内联视图,而不是topics
表。例如:
SELECT n.titel
, n.datum
, n.typ_news
, n.news
, n.verfasser
, n.time
, n.topicid
, t.id
, t.max_id2
FROM news n
LEFT
JOIN ( SELECT m.id
, MAX(m.id2) AS max_id2
FROM topics m
GROUP BY m.id
) t
ON t.id = n.topicid
ORDER BY n.id DESC LIMIT 10
选项2
如果id
表中的news
是UNIQUE(或PRIMARY KEY),那么您可以删除内联视图,加入topics
,并执行{{ 1}},像这样:
GROUP BY n.id
答案 2 :(得分:-1)
不够清楚。什么是列id = 1 id2 = 1等?两个表每个有2列?没有线索。
我正在考虑订单,但不知道你真正想要的是什么。
SELECT `MAX(`id2`) as MAX,`id` FROM `News` WHERE `id2` = `MAX`