Mysql如何获取子查询的列名?

时间:2016-10-08 09:50:31

标签: mysql

假设我有以下查询:

SELECT
    c.id AS 'course_id',u.id as 'user_id',c.round,u.first_name as name,u.last_name as family_name,u.`father_name`,u.`tazkera_id` as tazkira,c.`no` as class_ID,tc.province,tc.village,tl.id as training_provider_id,
    CASE c.`shift`
        WHEN 1 THEN 'Morning'
        WHEN 2 THEN 'Afternoon'
    END as shift,
    c.`start_date`as start_date,
    sa.participant_id,
    DATE_FORMAT(ca.`date`,'%Y-%m-%d') as attendence,
    CASE sa.`precence` 
        WHEN 0 THEN 'A' 
        WHEN 1 THEN 'P' 
    END as attendence_status 
FROM `users` AS u
LEFT JOIN `provinces` as pu On pu.`province_code` = u.`province_code`
LEFT JOIN `districts` as du on du.`district_code` = u.`district_code`

LEFT JOIN `course_user` as cu ON cu.`user_id` = u.id AND cu.`relation_type` = 1
LEFT JOIN `courses` AS c On c.id = cu.`course_id`


LEFT JOIN `training_centers` as tc On tc.id = c.`training_center_id`
LEFT JOIN `training_providers` AS tl ON tl.id = tc.`training_provider_id`
/*** Training location **/
LEFT JOIN `provinces` as pt On pt.`province_code` = tc.`province`
LEFT JOIN `districts` as dt on dt.`district_code` = tc.`district`
LEFT JOIN `course_attendances` as ca ON ca.`course_id` = c.`id`
LEFT JOIN `student_attendances` as sa ON sa.`course_attendance_id` = ca.`id`

WHERE c.id IS NOT NULL AND sa.`participant_id` = u.id
GROUP BY sa.`participant_id`,ca.date order by u.id,ca.date

我想用mysql获取上述查询的列名。 当然用php我们可以做到这一点,但我的问题是,如何用mysql查询呢?有可能吗?

1 个答案:

答案 0 :(得分:0)

MySQL仅仅是数据库系统。你告诉它要选择什么,它会这样做。在您的情况下,您告诉它选择courses.id并将其命名为course_id,依此类推。列名隐含在结果中。这样的工作方式如下:您的应用程序将查询发送到MySQL; MySQL检查它并告诉你它是否可以。你的应用要求列; MySQL告诉你列名和类型。你的应用要求行; MySQL发送它们。

通常你会使用一个自动完成所有操作的应用程序,例如phpMyAdmin。当您自己编写这样的应用程序时,该语言通常会隐藏所有这些(比如Java框架或.NET)。但是,当然你也可以明确地要求列名和类型,例如用PHP:

mysqli_fetch_field_direct($result, $column_index)

您可能只需搜索“MySQL”+<有问题的语言>,就可以找到有关如何执行此操作的详细信息。 +“列名”。