背景
我有一个 Web 应用程序,它必须从其他表中删除条目,通过从表 1 中选择的“tielists”进行过滤 -> item_table 1、表 2、表 3....现在基本上我的结果集将是肮脏的大,除非我使用来自另一个表的过滤语句,使用 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....
边注
在任何一个 tielist 中,只有一个汽车 ID 会出现一次。
此选择语句必须使用 user_id = $variable... 进行过滤(记住,我也在寻找哪个汽车 ID)
我必须有它来自的 tielist 的名称才能被回显到一个变量中...
我只会在任何给定时间寻找一个
id_of_car
,因为此选择将包含在 foreach 循环中。我在想
union all
items 可以用来选择行,但我如何才能获得该行所在的 tielist 的名称,以及过滤器如何从 user_id 行使用
最佳答案
如果你想要性能,我建议使用 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
子句以根据需要进行过滤。
如果您为每个 tielist 表在 id_of_car
上建立索引,那么性能应该相当不错。如果 where
子句在第一个表上使用索引,那么连接和 where 都应该使用索引,查询会非常快。
关于mysql - 使用另一个表的过滤器从 Union x 3 中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16596797/