MySQL 查询 - 更优雅的选择?在 SELECT 中的多个表中引用相同的列名
MySQL query - more elegant option? Referencing same column name in multiple tables in a SELECT
我在 MySQL 数据库中有几个 table,大多数 SELECT 查询将引用每个 table 中具有相同值的同名列.
因此,例如,tables(bnsf、train_plan、train_type 和 operation_costs)将 ALL有一个名为“train_id”的字段。
根据 record/row,'train_id' 列上的值可能是 1、2、3、4、5 等。但大多数时候在查询中,所需的结果将全部用于这些值与给定值匹配的记录,例如“2”。
So a query like this works:
SELECT * FROM (((bnsf
INNER JOIN train_plan ON bnsf.train_id = train_plan.train_id)
INNER JOIN train_type ON train_plan.train_id = train_type.train_id)
INNER JOIN operation_costs ON train_type.train_id = operation_costs.train_id)
WHERE bnsf.train_id = 2
AND train_plan.train_id = 2
AND train_type.train_id = 2
AND operation_costs.train_id = 2;
Is there a simpler way of writing that query (specifically the WHERE
clause)? Essentially, something like this:
WHERE `train_id` IN TABLE(bnsf, train_plan, train_type, operation_costs) = 2;
// invalid syntax
我想避免使用 AND、AND、AND - 并且必须为每个 table 重复相同的值。我有什么作品,但看起来不是很优雅。有什么想法吗?
我看了很久其他的帖子,但是我不喜欢工会的建议等等(好像没有更短)
您的连接条件使除了第一个 WHERE 子句之外的所有子句都是多余的。
INNER JOIN train_plan ON bnsf.train_id = train_plan.train_id)
只有 train_plan
行匹配 bnsf.train_id
被选中,类似地
其他表进一步加入。
所以当你说,
WHERE bnsf.train_id = 2
然后在该列上加入其他表,可以保证它们都相同。
SELECT * FROM (((bnsf
INNER JOIN train_plan ON bnsf.train_id = train_plan.train_id)
INNER JOIN train_type ON train_plan.train_id = train_type.train_id)
INNER JOIN operation_costs ON train_type.train_id = operation_costs.train_id)
WHERE bnsf.train_id = 2
这是一个非常合理的查询。
我在 MySQL 数据库中有几个 table,大多数 SELECT 查询将引用每个 table 中具有相同值的同名列.
因此,例如,tables(bnsf、train_plan、train_type 和 operation_costs)将 ALL有一个名为“train_id”的字段。
根据 record/row,'train_id' 列上的值可能是 1、2、3、4、5 等。但大多数时候在查询中,所需的结果将全部用于这些值与给定值匹配的记录,例如“2”。
So a query like this works:
SELECT * FROM (((bnsf
INNER JOIN train_plan ON bnsf.train_id = train_plan.train_id)
INNER JOIN train_type ON train_plan.train_id = train_type.train_id)
INNER JOIN operation_costs ON train_type.train_id = operation_costs.train_id)
WHERE bnsf.train_id = 2
AND train_plan.train_id = 2
AND train_type.train_id = 2
AND operation_costs.train_id = 2;
Is there a simpler way of writing that query (specifically the WHERE clause)? Essentially, something like this:
WHERE `train_id` IN TABLE(bnsf, train_plan, train_type, operation_costs) = 2;
// invalid syntax
我想避免使用 AND、AND、AND - 并且必须为每个 table 重复相同的值。我有什么作品,但看起来不是很优雅。有什么想法吗?
我看了很久其他的帖子,但是我不喜欢工会的建议等等(好像没有更短)
您的连接条件使除了第一个 WHERE 子句之外的所有子句都是多余的。
INNER JOIN train_plan ON bnsf.train_id = train_plan.train_id)
只有 train_plan
行匹配 bnsf.train_id
被选中,类似地
其他表进一步加入。
所以当你说,
WHERE bnsf.train_id = 2
然后在该列上加入其他表,可以保证它们都相同。
SELECT * FROM (((bnsf
INNER JOIN train_plan ON bnsf.train_id = train_plan.train_id)
INNER JOIN train_type ON train_plan.train_id = train_type.train_id)
INNER JOIN operation_costs ON train_type.train_id = operation_costs.train_id)
WHERE bnsf.train_id = 2
这是一个非常合理的查询。