两个查询联合问题

时间:2016-09-25 14:19:30

标签: mysql

我目前正在处理一个小的PHP脚本,我需要在其上执行联合查询。 我想从查询中获取7个元素,而另一个查询中的1个元素都在同一个表上执行。 第一个是:

select * from quiz  
where id != '10' 
  and langage = 'ar' 
order by qid DESC 
limit 1

第二个是:

SELECT * FROM (
                select * from quiz 
                where id != '10' 
                  and langage = '$loga' 
                order by nshares DESC 
                LIMIT 15) a 
order by rand() 
limit 7 
union 
select * from quiz  
where id != '10' 
  and langage = '$loga' 
order by qid DESC 
limit 1

我试过

import caffe
caffe.set_mode_cpu()
import numpy as np
from numpy import prod, sum
from pprint import pprint

def print_net_parameters (deploy_file):
    print "Net: " + deploy_file
    net = caffe.Net(deploy_file, caffe.TEST)
    print "Layer-wise parameters: "
    pprint([(k, v[0].data.shape) for k, v in net.params.items()])
    print "Total number of parameters: " + str(sum([prod(v[0].data.shape) for k, v in net.params.items()]))

deploy_file = "/home/ubuntu/deploy.prototxt"
print_net_parameters(deploy_file)

# Sample output:
# Net: /home/ubuntu/deploy.prototxt
# Layer-wise parameters: 
#[('conv1', (96, 3, 11, 11)),
# ('conv2', (256, 48, 5, 5)),
# ('conv3', (384, 256, 3, 3)),
# ('conv4', (384, 192, 3, 3)),
# ('conv5', (256, 192, 3, 3)),
# ('fc6', (4096, 9216)),
# ('fc7', (4096, 4096)),
# ('fc8', (819, 4096))]
# Total number of parameters: 60213280

但它似乎不起作用。任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

你很亲密。您只需要在子查询周围使用括号:

(select q.*
 from (select q.*
       from quiz q
       where id <> '10' and langage = '$loga'
       order by nshares DESC
       limit 15
      ) q
 order by rand()
 limit 7
) union
(select q.*
 from quiz q
 where id <> '10' and langage = '$loga'
 order by qid desc
 limit 1
);

{{3}}是一个SQL小提琴,显示语法有效。

注意:

  • union会产生开销以删除重复项。如果您不想要这种开销,则应使用union all
  • 您的查询可以返回7行或8行(假设有足够的匹配数据),因为第二个查询中的随机行可能与第一个查询匹配。
  • 您的语法错误是因为order by仅在union / union all查询结束时允许(除非您使用子查询)。
  • 如果id是数字,请不要使用单引号进行比较。它会让人感到困惑,并且会使优化器混淆。