我有一个要求,我想用where子句和group by运行SELECT查询。它返回几行,我想从中选择数量最少的行。
示例:
table t1:
host_name application type
host1 app1 0
host2 app2 0
host3 app4 0
host1 app5 0
host2 app6 0
host1 app7 1
host2 app8 1
在上表中,我想获得负载最少的主机。
host1 运行app1
,app5
,app7
。
host2 运行app2
,app6
,app8
。
host3 仅运行app4
。
所以host3负载最少。当我运行查询时,输出应为“host3”。只能选择type=0
行。
我有解决方案。但它是否优化了?是否有最佳的实现方法?
SELECT host_name from (SELECT host_name, min(count) FROM (SELECT host_name, COUNT(*) as count FROM t1 where type=0 group by host_name) as Dup ORDER BY host_name);
提前致谢:)
答案 0 :(得分:1)
试试这个,它会返回host
个apps
的最少select `host_name`
from t1
where type = 0
group by `host_name`
order by count(`host_name`) ASC
limit 0,1
。
logger.info("************************Start of executeChannel() method*****************************");
Channel channel = session.openChannel("exec");
// below line avoids "sudo: no tty present and no askpass program" error
((ChannelExec) channel).setPty(true);
// this line ensures password prompt is not displayed after sudo user
/**
* -S The -S (stdin) option causes sudo to read the password from the standard input instead of the terminal device.
* -p The -p (prompt) option allows you to override the default password prompt and use a custom one.
*/
String filename = file.toString().replace("[", "").replace("]", "").replace(",", "");
System.out.println("sudo -S -p '' "+command+" "+filename+" server2:/dir1/dir2/dir3/");
((ChannelExec)channel).setCommand("sudo -S -p '' "+command+" "+filename+" server2:/dir1/dir2/dir3/");
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
OutputStream out=channel.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
channel.connect();
out.write((pwd+"\n").getBytes());
byte[] tmp=new byte[1024];
while(true){
logger.info("start of while(true) method, is channel connected? "+channel.isConnected());
br.readLine();
while(br.readLine() != null){
System.out.println("channel.isConnected() "+channel.isConnected());
int i = in.read(tmp, 0, 1024);
if(i<0) break;
System.out.println("printing putty console: \n"+new String(tmp,0,i));
}
if (channel.isClosed()){
System.out.println("Exit Status:- "+channel.getExitStatus());
break;
}
try{
Thread.sleep(1000);
}
catch(Exception e) {
e.printStackTrace();
}
}
out.flush();
br.close();
System.out.println("DONE");
}