0

我在子句中写了一个带有IF()语句的查询WHERE

SELECT DISTINCT a.*, u.user_email, u.user_nicename, u.user_login, u.display_name
    (
        SELECT  b.date_recorded
        FROM    wp_bp_activity as b
        WHERE   b.type IN ( 'activity_comment','activity_update' )
           AND IF(b.type = 'activity_comment', b.item_id, a.id) = a.id
        ORDER BY b.item_id desc
        limit 0,1
    ) as drecord
FROM wp_bp_activity as a
LEFT JOIN wp_users as u ON a.user_id = u.ID
WHERE
   a.type IN ( 'activity_update' )
order by cast(drecord as datetime) desc
limit 0,20

但它给出了错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT b.date_recorded FROM wp_bp_activity as b WHERE b.' at line 3

这样的正确使用方法IF是什么?

4

3 回答 3

1

首先要更改的是在 . 之后添加逗号u.display_name。它应该有帮助。

于 2013-10-15T12:28:24.340 回答
1

您在 u.display_name ... 查询之后错过了一个逗号

SELECT DISTINCT a.*, u.user_email, u.user_nicename, u.user_login, u.display_name, 
(
    SELECT  b.date_recorded
    FROM    wp_bp_activity as b
    WHERE   b.type IN ( 'activity_comment','activity_update' )
       AND IF(b.type = 'activity_comment', b.item_id, a.id) = a.id
    ORDER BY b.item_id desc
    limit 0,1
) as drecord
FROM wp_bp_activity as a
LEFT JOIN wp_users as u ON a.user_id = u.ID
WHERE
  a.type IN ( 'activity_update' )
  order by cast(drecord as datetime) desc
 limit 0,20

希望这可以解决问题...因为我没有检查其他错误。

于 2013-10-15T12:28:37.183 回答
1

你甚至需要 if 吗?

((b.type = 'activity_comment' AND b.item_id = a.id) OR (b.type <> 'activity_comment'))

似乎是你想要做的

像其他人所说的 SQL 错误是缺少逗号

于 2013-10-15T12:54:22.020 回答