Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 按两个子查询中两列的差排序_Mysql_Sql_Sql Server - Fatal编程技术网

Mysql 按两个子查询中两列的差排序

Mysql 按两个子查询中两列的差排序,mysql,sql,sql-server,Mysql,Sql,Sql Server,我有两张桌子 Table1 with columns f_id, a_id Table2 with columns a_id, a_name 我试图找到一个查询,我可以通过两个子查询中a\u ids的计数之差来排序f\u ids。子查询1基本上类似于: SELECT f_id, count(a_id) FROM Table1 GROUP BY f_id 子查询2看起来有点像这样: SELECT Table1.f_id, count(Tabl

我有两张桌子

Table1 with columns
    f_id, a_id

Table2 with columns
    a_id, a_name
我试图找到一个查询,我可以通过两个子查询中
a\u id
s的计数之差来排序
f\u id
s。子查询1基本上类似于:

SELECT f_id,
       count(a_id) 
FROM Table1 
GROUP BY f_id
子查询2看起来有点像这样:

SELECT Table1.f_id, 
       count(Table1.a_id) 
FROM Table1, Table2 
WHERE
     Table1.a_id = Table2.a_id 

WHERE Table2.a_name= "User Input1" OR "User Input2" 
GROUP BY f_id
现在,主查询应该根据子查询计数的差异对
Table1
f_id
s进行排序,我希望您能理解,尽管我可能没有很好地解释它

样本数据和所需输出:

Table1 with columns
    f_id, a_id
    5,    3
    5,    4
    6,    2
    6,    3

Table2 with columns
    a_id, a_name
    2,    "foo"
    3,    "bar"
    4,    "too"
现在考虑到用户输入是bar,我希望有以下输出

Output with order by difference of the two counts:
   r_id     difference of counts
   5,       0
   6,       1

如果我理解正确,这就是您要寻找的:

SELECT t1.f_id, (t1.cnt1 - t2.cnt2) AS DifferenceOfCount
FROM (SELECT f_id, COUNT(a_id) AS cnt1
      FROM Table1 
      GROUP BY f_id) t1
INNER JOIN (SELECT Table1.f_id AS f_id, COUNT(Table1.a_id) AS cnt2
            FROM Table1 
            INNER JOIN Table2 
            ON Table1.a_id=Table2.a_id 
            WHERE Table2.a_name= "foo" OR table2.a_name = "bar" 
            GROUP BY f_id) t2
ON t1.f_id = t2.f_id
ORDER BY DifferenceOfCount
这是你可以看到它是如何工作的

您应该注意到,我使用内部联接语法来联接两个表,而不是使用旧的方式(这样做更好)

另外,如果这个查询需要用户输入,我认为您应该为此创建存储过程。。。这看起来就像你能看到的一样

注意:这是MySQL,但有些类似的东西(在Sql Server中可能应该是相同的),我不太确定您使用的是什么,因为您标记了它们


德国劳埃德船级社

发布示例数据和您所需的输出。同时检查您的第二个查询。它有语法错误添加示例数据,我希望它能有所帮助。非常感谢您的帮助,它可以正常工作!欢迎光临!我很高兴我能帮上忙。。。你的子查询几乎完成了全部工作,我只是让它们适合你需要的工作:)P.S.如果它是按预期工作的,那么你可以将此答案标记为已接受:)