如何从联接表中选择最大表?

时间:2018-11-29 08:47:36

标签: mysql mysqli

大家好,我的表名为<%@ WebHandler Language="C#" Class="API" %> using System; using System.Web; using System.Data; using System.Data.SqlClient; using System.IO; using Newtonsoft.Json; using System.Collections.Generic; using Newtonsoft.Json.Linq; using System.Web.Script.Serialization; public class User { public string type { get; set; } public string user { get; set; } public string pass { get; set; } } public class API : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string strJson = new StreamReader(context.Request.InputStream).ReadToEnd(); User user = JsonConvert.DeserializeObject<User>(strJson); string str = System.Configuration.ConfigurationManager.ConnectionStrings["conStr"].ConnectionString, json = ""; if (user.type != null && user.user != null && user.pass != null) { SqlConnection con = new SqlConnection(str); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandText = "SELECT ID,UserName From Partner Where UserName=@UserName And PassWord=@Pass"; cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 100).Value = user.user; cmd.Parameters.Add("@Pass", SqlDbType.NVarChar, 100).Value = user.pass; if (ConnectionState.Closed == con.State) con.Open(); DataTable datatable = new DataTable(); SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd); con.Close(); sqlDataAdapter.Fill(datatable); if (datatable.Rows.Count > 0) { foreach (DataRow dr in datatable.Rows) //My data return; } } } ,而另一个表的名称为posts

在我的counttbl表中有列名

post

postid(primarykey), postdetails, postdate(timestamp) 中有3列

counttbl

我想从id(primarykey), postid,countnumber 中选择具有counttbl个计数的帖子,

例如:我在邮局表中

maximumnumber

在数量上有postid = 1, postdetails = details1, date = 29:11:00 00:00:00 postid = 1countnumber = 4postid = 2

然后我要选择具有countnumber = 3个计数数字的帖子,并使用join显示该帖子的详细信息。

我是这个新手,请帮忙

5 个答案:

答案 0 :(得分:1)

此语句将为您提供所需的结果。 我将表和字段命名为“ different”,因为它们可能与SQL中的保留字冲突。

SELECT * FROM 
(
  SELECT counts.postid, counts.counts 
  FROM counts 
  WHERE counts.counts = (SELECT max(counts) FROM counts) 
) tempcounts 
INNER JOIN posts ON posts.postid = tempcounts.postid 
ORDER BY posts.postdate DESC limit 0,1

如果更多的帖子具有相同的计数,则所有帖子都会出现在结果中

答案 1 :(得分:1)

请使用以下查询:

SELECT MAX(cnt.countnumber), cnt.postid
FROM counttbl as cnt
JOIN post as pst ON cnt.postid = pst.id

我给了表名:

表名: post and counttbl

答案 2 :(得分:0)

您可以在下面尝试

select * from posts p 
inner join 
(
  select postid, max(countnumber) from counttbl group by postid
) as p1
on p.postid=p1.postid

答案 3 :(得分:0)

尝试一下:

select * from post where postid in (select postid from counttbl having max(countnumber));

答案 4 :(得分:0)

尝试

从其中post_id IN的帖子中选择*(从counttble中选择MAX(countnumber))