简体   繁体   English

将多个查询合并为一个查询

[英]Combining multiple queries into a single one

I have a simple query:我有一个简单的查询:

SELECT t1.tbl, 
       t1.slug
FROM t1
WHERE tags = '%".$tag."%' 

However, I need to augment my results with the data from other tables (t2, t3, t4 and t5).但是,我需要使用其他表(t2、t3、t4 和 t5)中的数据来扩充我的结果。 For example, if t1.tbl = 't2' I need to add from:例如,如果t1.tbl = 't2'我需要添加:

SELECT t2.title
FROM t2    
WHERE t2.county = '".$county."'

which I could join like this:我可以这样加入:

LEFT JOIN ON (t1.rid = t2.id)

In each of there tables I'll filter by $county even though the column is named differently.在每个表中,即使列的名称不同,我也会按 $county 进行过滤。

I've tried something like this:我试过这样的事情:

SELECT t1.tbl, 
       t1.slug
FROM t1 A
LEFT JOIN (
   SELECT title
   FROM t2 B
   WHERE A.tbl = 't2'
) ON (A.rid = B.id)
WHERE A.tags = '%".$tag."%'

Is there a way to combine all there into a single query?有没有办法将所有这些组合成一个查询?

SELECT A.tbl, 
       A.slug,
       COALESCE(B.title, C.title) AS title
FROM t1 A
LEFT JOIN t2 B
  ON A.tbl = 't2' AND A.rid = B.id AND B.county = ?
LEFT JOIN t3 C
  ON A.tbl = 't3' AND A.rid = C.id AND C.region = ?
WHERE A.tags LIKE ?
  AND COALESCE(B.id, C.id) IS NOT NULL;

The last condition is to return only rows from A that have a match among one of the joined tables.最后一个条件是仅返回 A 中在其中一个连接表中匹配的行。

I think that's enough to see the pattern, so you can add more tables.我认为这足以看到模式,因此您可以添加更多表格。

I urge you to learn to use query parameters instead of concatenating variables directly into your SQL string.我敦促您学习使用查询参数,而不是将变量直接连接到 SQL 字符串中。 It's easier to write the code and more secure from SQL injection vulnerabilities if you use query parameters.如果您使用查询参数,则更容易编写代码并且更安全地避免 SQL 注入漏洞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM