我目前正在尝试构建一个有些棘手的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"

从基础上讲,我想做的是能够通过弦乐选择/组(图片螺纹已螺纹)而没有重复。此外,我想选择最新的stringID行(上面的示例是唯一的3)。

因此,如果我要查询数据库,它将返回以下内容(最新的唯一IDID):

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.

我希望这是有道理的。谢谢你的帮助。

有帮助吗?

解决方案

尝试以下内容。它可能不是最有效的查询,但它将起作用:

SELECT uniqueID, stringID, subject
FROM data_table
WHERE uniqueID IN
 (
  SELECT MAX(uniqueID) 
  FROM data_table
  GROUP BY stringID
 )
ORDER BY uniqueID DESC

其他提示

SELECT DISTINCT(a),
  ( SELECT DISTINCT(b) ) AS b,
  ( SELECT DISTINCT(c) ) AS c

FROM tblMyTBL

WHERE...
Order By...
Etc.

编辑: 基于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 价值。

我有类似的情况,发现了不同的查询。尝试这个:

SELECT MAX(uniqueID), stringID, subject
 FROM data_table
 GROUP BY stringID
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);
        }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top