简体   繁体   English

MySQL查询嵌套查询

[英]MySQL query nested query

I`m trying to run a nested query on MySQL (phpmyadmin) and via PHP, and both result in the same output which is incorrect. 我正在尝试在MySQL(phpmyadmin)和通过PHP上运行嵌套查询,并且两者都会导致相同的输出,这是不正确的。

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)

If multiple rows are expected from the subquery, use WHERE ID IN (SELECT...) instead of WHERE ID=(SELECT...) 如果期望子查询有多行,请使用WHERE ID IN (SELECT...)代替WHERE ID=(SELECT...)

You'll probably get better performance with a JOIN though: 使用JOIN可能会获得更好的性能:

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

Your nested query is wrong, it should look like this: 您的嵌套查询是错误的,它应如下所示:

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

In your case, you're comparing table1.ID with a string containing the second query. 在您的情况下,您正在将table1.ID与包含第二个查询的字符串进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM