简体   繁体   English

将同一个表的多个查询组合到一个SQL语句中

[英]Combining multiple queries of the same table into one SQL statement

I am trying to combine these MySQL queries but not getting them right. 我试图结合这些MySQL查询,但没有让他们正确。 Here is the pseudocode that I am hoping to combine to get a single line sql statement. 这是我希望结合起来获得单行sql语句的伪代码。

$var1 = "abc"
$var2 = "def"

IF ( $var1 IN (SELECT DISTINCT col1 FROM t1) )
{
    SELECT colA, colB, colC FROM t1 WHERE col1 = $var1 AND col2 LIKE '%$var2%'
}
ELSE
{
    SELECT colA, colB, ColC FROM t1 WHERE col2 LIKE %$var1%
}

Thanks 谢谢

First let me say that mjfgates could be right. 首先让我说mjfgates可能是正确的。 The original psuedo code is not "bad" just because it takes two steps. 原始的伪代码并不是“坏”,因为它需要两个步骤。 The more complex your SQL statement that greater chance the query engine may not find an optimal plan. SQL语句越复杂,查询引擎就越有可能找不到最佳计划。 In this particular case that's less likely because there's just a single table we're referencing multiple times, but it is something to keep in mind in general in these situations. 在这种特殊情况下,由于只有一个表我们引用了多次,所以不太可能,但在这些情况下,一般要记住这一点。 Getting a SQL down to one statement is not always a worthy goal in itself. 将SQL简化为一个语句本身并不总是一个有价值的目标。

Now to answer your question: 现在回答你的问题:

   select colA,colB,colc from table1 t1
    where 
    (
    (col1 = $var1 and col2 like '%$var2%') and 
            EXISTS (select 1 from table1 t2 where t2.col1 = $var1)
    )
    or 
    (
    (col2 LIKE %$var1%) and 
           NOT EXISTS (select 1 from table1 t3 where t3.col1 = $var1)
    )

I think... I wouldn't do it. 我想......我不会这样做。 This is just the sort of thing that stored procedures and views, each of which DO have the if statement, were made for. 这就是存储过程和视图的东西,每个过程都有DO语句。 Just run the selects in order from most specific to least, and return the first result that gives rows. 只需从最具体到最少的顺序运行选择,并返回给出行的第一个结果。

Also, I might see a bug here. 另外,我可能会在这里看到一个错误。 What happens if there are items in the table where col1 = $var1, but none of those items have col2 like $var2 ? 如果表中有col1 = $ var1的项目,但这些项目中没有一个像$ var2那样的col2,会发生什么? What is supposed to happen? 应该发生什么?

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

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