查询的逆运算

gr8qqesn  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(247)

以下查询的反方向是什么:

SELECT * FROM `test_result` 
INNER JOIN `perinfo` ON `test_result`.`mobileno` = `perinfo`.`mobileno` 
WHERE `perinfo`.`insti_id` = '2' 
  AND `test_id` = (SELECT `test_id` 
                   FROM `test` 
                   WHERE `test_name` = 'One')

我想从数据库表'perinfo'中选择行,其中insti\u id为2,并且它们也存在于数据表'test\u result'中

myss37ts

myss37ts1#

我不明白你所说的“查询的倒数”是什么意思,但要得到你在问题文本中描述的结果,你应该使用它

SELECT *
  FROM `perinfo`
  INNER JOIN `test_result` 
    ON `test_result`.`mobileno` = `perinfo`.`mobileno` 
  WHERE `perinfo`.`insti_id` = '2'

换言之,只要颠倒 perinfo 以及 test_result 在查询中,并删除子选项 test 因为它没有被指定为期望结果的一部分。

xkftehaa

xkftehaa2#

你可以改变你的过滤器 != (不相等)条件代替 = (相等)

SELECT * FROM `test_result` 
  INNER JOIN `perinfo` ON `test_result`.`mobileno` = `perinfo`.`mobileno` 
  WHERE `perinfo`.`insti_id` != '2' 
    AND `test_id` != (SELECT `test_id` 
                     FROM `test` 
                     WHERE `test_name` = 'One')

但如果子查询的结果多于,则应该在中或不在中

SELECT * FROM `test_result` 
  INNER JOIN `perinfo` ON `test_result`.`mobileno` = `perinfo`.`mobileno` 
  WHERE `perinfo`.`insti_id` != '2' 
    AND `test_id` NOT IN  (SELECT `test_id` 
                     FROM `test` 
                     WHERE `test_name` = 'One')
nhaq1z21

nhaq1z213#

试试这个:

SELECT * FROM `test_result` `t`
INNER JOIN `perinfo` ON `test_result`.`mobileno` = `perinfo`.`mobileno` 
WHERE `perinfo`.`insti_id` = '2' 
  AND NOT EXISTS(SELECT 1 FROM `test` 
                 WHERE `test_name` = 'One'
                   AND `test_id` = `t`.`test_id`)

相关问题