有两个表格文章和类别。
nid | title | status
---+-------------+-------
1 | abc | 1
2 | ggg | 1
3 | kkk | 0
4 | rrr | 1
5 | fff | 1
6 | ggg | 1
发布status = 1的地方。
cid | nid
---+-------------
1 | 1
2 | 2
2 | 3
3 | 4
1 | 5
2 | 6
现在我希望为每个cid获得一个nid,而不会出现状态为1的cid双重出现。
答案 0 :(得分:1)
您可以使用聚合:
select c.cid, max(c.nid)
from category c join
article a
on c.nid = a.nid
where a.status = 1
group by c.cid;
答案 1 :(得分:1)
您可以将GROUP BY
与JOIN
一起使用,例如:
SELECT t2.cid, MAX(t2.nid)
FROM table2 t2 JOIN table1 t1 ON t2.nid = t1.nid and t1.status = 1
GROUP BY t2.cid;
答案 2 :(得分:1)
首先,您必须决定在多个匹配的情况下为cid显示哪个nid。假设你想要最大的nid。从类别中选择并查找文章的状态。然后聚合。
select cid, max(nid)
from category
where nid in (select nid from article where status = 1)
group by cid;
答案 3 :(得分:0)
试试这个。
SELECT DISTINCT cid
FROM category AS a1
INNER JOIN article AS a2 ON a1.nid = a2.nid
WHERE a1.[STATUS] = 1