无法使用列进入子查询 - MySQL数据库

时间:2016-11-04 14:08:58

标签: mysql sql

我无法将此'enquiries.enquiry_id'列用于子查询。我也试过了别名的表,但没有成功 错误代码:1054。'where子句'

中的未知列'enquiries.enquiry_id'

我们可以用另一种方法吗?

Tables
------------------------------
Enquiries
------------------------------
enquiry_id | name 
1            A
2            B
3            C
4            D
------------------------------
Bookings
------------------------------
booking_id | name |enquiry_id 
1            A      1
2            B      2
3            C      2   
4            D      3
------------------------------


SELECT 
    (SELECT 
            COUNT(*)
        FROM
            (SELECT 
                booking_id
            FROM
                bookings
            WHERE
                enquiry_id = enquiries.enquiry_id) AS t) AS total
FROM
    enquiries
WHERE
    enquiry_id = 2

enter image description here

1 个答案:

答案 0 :(得分:4)

我认为您的查询可以简化为

SELECT COUNT(e.booking_id) as total
FROM  enquiries e
WHERE e.enquiry_id = 2

或者如果您需要booking

中的其他内容
SELECT COUNT(b.booking_id)  as total
FROM  bookings b
JOIN  enquiries e
  ON b.enquiry_id = e.enquiry_id 
WHERE e.enquiry_id = 2

并向您展示如何修复您的查询。

SELECT 
        (SELECT COUNT(*)
         FROM  bookings b
         WHERE b.enquiry_id = e.enquiry_id) AS total            
FROM
    enquiries e
WHERE
    enquiry_id = 2