mysql - mysql使用IF语句和子查询查询错误

标签 mysql sql

我(至少对我来说)有一个复杂的查询,是用这个网站的示例构建的。我添加的最后一件事是 IF 语句。如果没有 IF 语句,它将使用 IF 语句的 TRUE 部分。我希望你们能在这里帮助我。这是查询:

SELECT 
    t.ID, t.start_time, t.end_time, t.start_date, t.end_date, t.balance, 
    u1.first_name AS teacher_one_first_name, u1.last_name AS teacher_one_last_name, 
    u2.first_name AS teacher_two_first_name, u2.last_name AS teacher_two_last_name,
    company.name, company.post_city, tag, lvl,
    IF(
        t.balance=1,
        (
            (SELECT count(user_ID)
                FROM company_lesson_block_student
                WHERE lead_follow=0 AND company_lesson_block_ID=t.ID) AS lead,
            (SELECT count(user_ID)
                FROM company_lesson_block_student
                WHERE lead_follow=1 AND company_lesson_block_ID=t.ID) AS follow
        ),
            (SELECT count(user_ID)
                FROM company_lesson_block_student
                WHERE company_lesson_block_ID=t.ID) AS total_student
    )
    FROM company_lesson_block AS t
    LEFT JOIN company_lvl ON company_lvl.ID = t.lvl_ID
    LEFT JOIN tag ON tag.ID = t.style_ID
    LEFT JOIN company ON company.ID=t.location_ID
    LEFT JOIN user AS u1 ON t.teacher_one_ID=u1.ID
    LEFT JOIN user AS u2 ON t.teacher_two_ID=u2.ID
    WHERE t.company_ID='1' AND location_ID='1' AND company_season_ID='1'
    ORDER BY start_date ASC

我收到的错误消息是:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'AS lead, (SELECT count(user_ID) FROM company_less' at line 10

任何帮助/提示均适用

最佳答案

您想要返回 2 列,但 IF 只能返回 1 列,因此您需要 2 个 IF:

........................
IF(
    t.balance=1,
        (SELECT count(user_ID)
            FROM company_lesson_block_student
            WHERE lead_follow=0 AND company_lesson_block_ID=t.ID),
        (SELECT count(user_ID)
            FROM company_lesson_block_student
            WHERE company_lesson_block_ID=t.ID)
) AS ????,
IF(
    t.balance=1,
       (SELECT count(user_ID)
            FROM company_lesson_block_student
            WHERE lead_follow=1 AND company_lesson_block_ID=t.ID),
        (SELECT count(user_ID)
            FROM company_lesson_block_student
            WHERE company_lesson_block_ID=t.ID)
) AS ????
........................

您必须在IF 的右括号后设置别名。
也许您必须重新考虑这个逻辑,因为在 FALSE 的情况下,相同的值会返回两次。

关于mysql - mysql使用IF语句和子查询查询错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57944903/

相关文章:

mysql - 运行重新启动的查询

php - 无论如何改进这个 MySQL 数据库查询

mysql - 在 MySQL 中将 RGB 转换为 HSL

php - 将 Blob 内容插入另一个 Blob (MySQL)

sql - MERGE 语句问题 - 分号错误 (SQL Server 2008)

sql - 用基于规则/声明式的实现替换关系数据库(SQL Server)?

php - 如何上传多张图片并插入mysql的同一行

sql - T-SQL计算移动平均线

java - 跟踪数据库更改

php - 使用输入和输出参数创建 MySQL 存储过程