MySQL查询嵌套查询

MySQL查询嵌套查询

本文介绍了MySQL查询嵌套查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 MySQL (phpmyadmin) 和通过 PHP 上运行嵌套查询,两者都导致相同的输出,但不正确.

I`m trying to run a nested query on MySQL (phpmyadmin) and via PHP, and both result in the same output which is incorrect.

注意:由于项目的敏感性,表名已被剪掉

NOTE: Table name have been clipped due to sensitivity of project

SELECT * FROM `table1` WHERE ID="SELECT `field1` FROM `table2` WHERE ID=1"

这将返回零行,尽管每个查询单独给出如下有效输出

This returns zero rows, although each query alone gives a valid output as below

SELECT `field1` FROM `table2` WHERE ID=1

给出所需的输出,当在主查询的第一部分中使用时,这个输出也提供了所需的内容.请帮忙.

Gives the required output, and this output when used in the first part of the main query provides also what is required. Please help.

推荐答案

不要用引号将其括起来.而是将其括在括号中:

Don't enclose it in quotes. Instead enclose it in parentheses:

SELECT * FROM `table1` WHERE ID=(SELECT `field1` FROM `table2` WHERE ID=1)

如果子查询需要多行,请使用 WHERE ID IN (SELECT...) 而不是 WHERE ID=(SELECT...)

If multiple rows are expected from the subquery, use WHERE ID IN (SELECT...) instead of WHERE ID=(SELECT...)

不过,使用 JOIN 可能会获得更好的性能:

You'll probably get better performance with a JOIN though:

SELECT table1.*
FROM
  table1 JOIN table2 ON table1.ID = table2.field1
WHERE table1.ID = 1

这篇关于MySQL查询嵌套查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 08:59