区别,加入和If /作为MySQL查询

时间:2011-07-15 15:14:23

标签: mysql

这是问题 - 如何在不使用UNION或第二个选择查询的情况下进行以下工作?

代码:

$query = "SELECT DISTINCT(t.tid), IF(last_job2 <= 2000, last_job2, last_job) AS last_job
                      FROM smf_posts p
                        LEFT JOIN smf_topics t ON (p.topic_id=t.tid)"

因此,当我添加WHERE语句时,它可以识别last_job的if / as?

例如在下面的WHERE中

WHERE last_job&lt; 2000

换句话说,我想要这个“IF(last_job2&lt; = 2000,last_job2,last_job)AS last_job” 在到达“WHERE last_job&lt; 2000”时被识别。使用我当前的代码,它不遵循“IF(last_job2&lt; = 2000,last_job2,last_job)AS last_job”。

谢谢!

1 个答案:

答案 0 :(得分:0)

只是一个疯狂的猜测。你想要这个吗?:

SELECT DISTINCT(t.tid)
     , IF(last_job2 <= 2000, last_job2, last_job) AS last_job
FROM smf_posts p
  LEFT JOIN smf_topics t ON (p.topic_id=t.tid)
WHERE IF(last_job2 <= 2000, last_job2, last_job) < 2000

或者也许这样:

SELECT DISTINCT(t.tid)
     , IF(last_job2 <= 2000, last_job2, last_job) AS last_job
FROM smf_posts p
  LEFT JOIN smf_topics t
    ON (p.topic_id=t.tid)
    AND IF(last_job2 <= 2000, last_job2, last_job) < 2000