1

背景

我有一个 Web 应用程序,它必须从其他表中删除条目,通过从表 1 -> item_table 1、表 2、表 3 中选择的“tielists”进行过滤......现在基本上我的结果集将变得非常大,除非我使用另一个表中的过滤器语句,使用 user_id ......所以有人可以根据需要帮助我构建我的语句吗?泰!

cars_belonging_to_user
-----------------------------
ID | user_id | make   | model
----------------------------
1  |  1      | Toyota | Camry
2  |  1      |Infinity| Q55
3  |  1      | DMC    | DeLorean
4  |  2      | Acura  | RSX

Okay, Now the three 'tielists'
name:tielist_one
----------------------------
id | id_of_car | id_x | id_y|
1  | 1         | 12   | 22  |
2  | 2         | 23   | 32  |
-----------------------------
name:tielist_two
-------------------------------
id | id_of_car | id_x | id_z|
1  |  3        | 32   | 22  |
-----------------------------
name: tielist_three
id | id_of_car | id_x | id_a|
 1 | 4         | 45   | 2   |
------------------------------

结果集和代码

echo name_of_tielist_table
// I can structure if statements to echo result sets based upon the name
// Future Methodology: if car_id is in tielist_one, delete id_x from x_table, delete id_y from y_table...
// My output should be a double select base:
--SELECT * tielists from WHERE car_id is 1... output name of tielist... then
--SELECT * from specific_tielist where car_id is 1.....delete x_table, delete y_table...

考虑到列表会很大,而且 tielist 也同样长,我必须过滤结果car_id(id) = $variable && user_id = $id....

旁注

  1. 在任何一个 tielist 中,只有一个汽车 ID 会出现一次。

  2. 这个选择语句必须用 user_id = $variable... 过滤(记住,我也在寻找哪个汽车 id)

  3. 我必须有它来自的 tielist 的名称才能被回显到一个变量中......

  4. 我只会id_of_car在任何给定时间寻找一个,因为这个选择将包含在一个 foreach 循环中。

  5. 我在想一个union all项目可以用来选择行,但是我怎样才能得到该行所在的 tielist 的名称,以及如何从 user_id 行使用过滤器

4

1 回答 1

1

如果你想要性能,我会建议left outer join而不是union all. 这将允许查询为您的目的有效地使用索引。

根据你所说的,一辆车正好在其中一个列表中。这对于这种方法的工作很重要。这是SQL:

select cu.*,
       coalesce(tl1.id_x, tl2.id_x, tl3.id_x) as id_x,
       tl1.y, tl2.idz, tl3.id_a,
       (case when tl1.id is not null then 'One'
             when tl2.id is not null then 'Two'
             when tl3.id is not null then 'Three'
        end) as TieList
from Cars_Belonging_To_User cu left ouer join
     TieList_One tl1
     on cu.id_of_car = tl1.id_of_car left outer join
     TieList_Two tl2
     on cu.id_of_car = tl2.id_of_car left outer join
     TieList_Three tl3
     on cu.id_of_car = tl3.id_of_car;

然后,您可以根据需要添加一个where子句进行过滤。

如果id_of_car每个 tielist 表都有一个索引,那么性能应该是相当不错的。如果where子句在第一个表上使用索引,那么连接和 where 都应该使用索引,并且查询会很快。

于 2013-05-16T21:00:05.737 回答