如果表 2 中的列 = 1,则 MySql 从表 1 中选择

标签 mysql

我需要从 table1 返回一个列,如果 table2 中的列具有相同的标识符但列名不同,并且有一个 1在特定领域。

表 1

table1

表2

table2

在这个例子中,我想从 table1 中检索 item_code 222,其中 alt1888 ,但仅当 table2 中的 itemalt11 时。

我已经尝试了很多内联查询和 LEFT JOIN 变体,但似乎没有任何东西能够真正执行任务。写出我尝试过的所有版本是没有意义的,因为它们都不起作用,但一个例子是:

SELECT item_code FROM table1 WHERE alt1 = "888" 
AND (SELECT item FROM table2 WHERE item = "222" AND alt1 = 1)

以上可能不是我尝试过的最好的例子,但由于到目前为止它们都不起作用,所以这并不重要。非常感谢任何帮助。

最佳答案

试试这个

SELECT item_code from table1 INNER JOIN 
table2
ON table1.item_code = table2.item where table2.alt1 = 1 and table1.alt1 = 888

希望这能奏效。

关于如果表 2 中的列 = 1,则 MySql 从表 1 中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40286436/

相关文章:

php - 纬度和经度值保存为字符串还是数字?

mysql - 导入大型 SQL 文件

MySQL 列 : Change existing phone numbers into specific format?

php - 如何计算以天为单位的持续时间?

mysql - 从命令行将 MySQL 变量传递给脚本

sql - 我的应用程序如何从临时表中获益?

python - 在 Django 中创建用户 : User, Staff, SuperUser

mysql - 使用存储过程计算团队中的人数

mysql 错误代码 : 1066. 不唯一的表/别名: 't2'

php - SQLSTATE[HY093] : Invalid parameter number: number of bound variables does not match number of tokens - help needed