基于条件的选择和连接查询

时间:2011-10-18 22:18:00

标签: mysql

查询1:

SELECT if(COUNT(0),1,0) as 'IsPresent'
FROM table1
WHERE Id=1500;    

QUERY2:

如果IsPresent为1,那么

select t2.mark,t2.age from table2  t2,table1 t1
where  t1.ID=t2.ID order by t1.ID;

如果IsPresent为0,那么

select mark,age from table2;

即。如果表中存在条目,我需要加入其他,我不需要加入。

我们有什么办法可以用一个mysql选择查询来实现这个目的吗?

2 个答案:

答案 0 :(得分:1)

我认为你可以将两个不同的查询案例结合起来:

SELECT T2.MARK, T2.AGE
FROM TABLE1 T1, TABLE2 T2
WHERE
  T1.ID=T2.ID AND
  T1.ID=1500
UNION
SELECT MARK, AGE
FROM TABLE1
WHERE
  NOT ID=1500

答案 1 :(得分:1)

    SELECT t2.mark, t2.age
    FROM table2 t2
      JOIN table1 t1
        ON t1.id = t2.id
    WHERE EXISTS
          ( SELECT *
            FROM table1
            WHERE id=1500
          )
  UNION ALL
    SELECT t2.mark, t2.age
    FROM table2 t2
    WHERE NOT EXISTS
          ( SELECT *
            FROM table1
            WHERE id=1500
          )

可以简化为:

    SELECT t2.mark, t2.age
    FROM table2 t2
      LEFT JOIN table1 t1
        ON  t1.id = t2.id
        AND EXISTS
            ( SELECT *
              FROM table1
              WHERE id=1500
            )