我目前正在尝试构建一个有点棘手的MySQL Select语句。以下是我要完成的任务:
我有一张这样的表:
data_table
uniqueID stringID subject
1 144 "My Subject"
2 144 "My Subject - New"
3 144 "My Subject - Newest"
4 211 "Some other column"
基本上,我想要做的是能够SELECT / GROUP BY stringID(stringID是线程化的图片)而不是重复。此外,我想选择最近的stringID行(在上面的示例中是uniqueID 3)。
因此,如果我要查询数据库,它将返回以下内容(最新的uniqueID位于顶部):
uniqueID stringID subject
4 211 "Some other column"
3 144 "My Subject - Newest" //Notice this is the most recent and distinct stringID row, with the proper subject column.
我希望这是有道理的。谢谢你的帮助。
答案 0 :(得分:9)
尝试以下方法。它可能不是最有效的查询,但它可以工作:
SELECT uniqueID, stringID, subject
FROM data_table
WHERE uniqueID IN
(
SELECT MAX(uniqueID)
FROM data_table
GROUP BY stringID
)
ORDER BY uniqueID DESC
答案 1 :(得分:3)
SELECT DISTINCT(a),
( SELECT DISTINCT(b) ) AS b,
( SELECT DISTINCT(c) ) AS c
FROM tblMyTBL
WHERE...
Order By...
Etc.
答案 2 :(得分:2)
修改:根据评论中OP提供的新信息,最好依赖uniqueID
:
select t.uniqueID
, t.stringID
, t.subject
, t.your_timestamp_col
from data_table t
left outer join data_table t2
on t.stringID = t2.stringID
and
t2.your_timestamp_col > t.your_timestamp_col
where t2.uniqueID is null
如果像lexu在评论中提到的那样,您确定最高uniqueID
值始终与最新主题相对应,那么您可以这样做:
select t.uniqueID
, t.stringID
, t.subject
from data_table t
left outer join data_table t2
on t.stringID = t2.stringID
and
t2.uniqueID > t.uniqueID
where t2.uniqueID is null
这基本上意味着:只返回data_table
中没有更高uniqueID
值的记录。
答案 3 :(得分:0)
我有类似的情况,发现了不同的查询。试试这个:
SELECT MAX(uniqueID), stringID, subject
FROM data_table
GROUP BY stringID
答案 4 :(得分:-1)
private void LoadAllFamilyMembers(string relationShip)
{
lbFamilyMembers.SelectedIndexChanged -= new EventHandler(lbFamilyMembers_SelectedIndexChanged);
SqlCommand cmd = new SqlCommand("select familymemberid,name from FamilyMembers where relationship = @relationship", con);
cmd.Parameters.AddWithValue("@relationship", relationShip);
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
lbFamilyMembers.DataSource = dt;
lbFamilyMembers.DisplayMember = "name";
lbFamilyMembers.ValueMember = "familymemberid";
lbFamilyMembers.SelectedIndex = -1;
lbFamilyMembers.SelectedIndexChanged += new EventHandler(lbFamilyMembers_SelectedIndexChanged);
}