SQL JOIN与日期'类别'

时间:2015-09-14 13:12:22

标签: php mysql sql join syntax

我正在尝试创建一个将成员分组为儿童和成人的查询:

mysql ticket:

|ticket_id|ticket_no|
|    1    | 123456  |

mysql成员:

|member_id|ticket_no|  name  |    dob     |
|    1    | 123456  | edward | 2010-03-05 | //child
|    2    | 123456  | karen  | 1965-03-05 | //adult

html输出:

|ticket_no|Adult Names|Children Names|
| 123456  |   karen   |    edward    |

我想真的使用连接查询并将其作为一行循环输出。 这只是一个例子:

SELECT t.*, m.*
FROM (`tickets` t)
JOIN(`members` m)
    ON(m.`ticket_no` = t.`ticket_no`)
    (SELECT m.`name` FROM m WHERE m.`dob` BETWEEN {$cStart} AND {$cEnd}) as children
    (SELECT m.`name` FROM m WHERE m.`dob` BETWEEN {$aStart} AND {$aEnd}) as adults
ORDER BY t.`ticket_no`

非常感谢任何帮助。

使用SQL:

        SELECT t.*,
        CASE
            WHEN m.`dob`
                BETWEEN '{$datetime['start']}'
                AND '{$datetime['end']}'
            THEN m.`name`
        END AS ChildName
        FROM `tickets` t
        JOIN (`members` m)
            ON (m.`ticket_no` = t.`ticket_no`)
        ORDER BY t.`ticket_no`

1 个答案:

答案 0 :(得分:1)

你可以试试这个。只需在您正在使用的变量中传递适当的日期范围

    SELECT t.ticket_no,
    case when m.`dob` BETWEEN {$aStart} AND {$aEnd} then m.name  end as AdultName,
 case when m.`dob` BETWEEN {$cStart} AND {$cEnd} then m.name end as ChildName
     FROM (`tickets` t)
    JOIN(`members` m)
        ON(m.`ticket_no` = t.`ticket_no`)
    ORDER BY t.`ticket_no`