我具有以下数据库结构:
String sql = " "
+ "SET NOCOUNT ON; "
+ "DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX); "
+ " "
+ "SET @cols = "
+ " STUFF( "
+ " ( "
+ " SELECT distinct ',' + QUOTENAME([case owner]) "
+ " FROM StatusTable c "
+ " FOR XML PATH(''), TYPE "
+ " ).value('.', 'NVARCHAR(MAX)'), "
+ " 1, "
+ " 1, "
+ " ''); "
+ " "
+ "set @query = 'select * "
+ "from "
+ "( "
+ " select [case owner], [time taken(minutes)] from StatusTable "
+ ") as pivotdata "
+ "pivot( "
+ " sum([time taken(minutes)]) for [CASE OWNER] in ('+@cols+') "
+ ") as pivoting'; "
+" "
+ "execute(@query); ";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
// print column headings
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.printf("%5s", rsmd.getColumnLabel(i));
}
System.out.println();
rs.next();
// print column values
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.printf("%5s", rs.getString(i));
}
System.out.println();
/* console output:
AAA BBB XXX
2 13 1
*/
现在,我要查找所有没有将特定属性设置为true的孩子的父母。
示例:
Parent
-> child 1
-> child 2
->..
目前,我有以下内容:
Should not be found:
Parent:
-> child 1 (selected: true)
-> child 2 (selected: false)
Should be found
Parent:
-> child 1 (selected: nil)
-> child 2 (selected: false)
这很好用,但似乎效率低下。我相信应该有一个更简便,更快捷的方法。
答案 0 :(得分:0)
parents = Parent.joins(:children).where('children.selected = FALSE or children.selected is NULL')
此查询从父子内部联接表中选择行,且所选属性未设置为true。
如果想要父对象甚至没有关联的子代,则必须保留外部联接子代。
Parent.joins('left join children on parents.id = childrenparent_id')..where('children.selected = FALSE or children.selected is NULL')
答案 1 :(得分:0)
您只能使用where.not解决它。
请参阅 https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods/WhereChain.html#method-i-not
Project.joins(:project_images).where.not(project_images: { selected: true })
答案 2 :(得分:0)
Project.joins(:project_images).where(“ project_images.selected NOT IN(TRUE)”);