0

使用单个查询,我需要获取所有对象 A 的列表和一个附加列,当与表 B 中的对象 C 有关联时返回“1”,或者在没有与对象 C 的关联时返回“0”在表 B 中。

表 A 保存所有对象 A 表 B 保存与另一个对象 C 关联的所有对象 A。

我知道对象 C 的 ID。

目前我正在使用带有 LEFT JOIN 的查询和两个带有 AND 的 JOIN 条件。对于返回值列,我使用“(TableB.id IS NOT NULL) as associated”。

表 A 可能只保存几十到一百条记录。表 B 可能会保存数千到数十万条记录。表 C 可能会保存数千到数十万条记录。

TableA.id is index
TableB.tablea_id is index
TableB.id is index
TableB.tablec_id is index
TableC.id is index

我的查询目前如下所示:

SELECT TableA.name, TableA.code, (TableB.id IS NOT NULL) AS associated
FROM TableA 
LEFT JOIN TableB ON TableA.id=TableB.tablea_id AND TableB.tablec_id = $input

我用于 SQL 查询的方法或实现预期结果的更好方法是否存在任何性能问题?

4

1 回答 1

0

Your query looks fine as far as I can see.

However, you should keep in mind that conditions on join should be for matching foreign keys. Following this practice at least makes your queries more readable and maintainable.

于 2012-05-19T12:56:12.583 回答