我有下表(lecture_table)
------------------------------------------------------------------------
| lecture_name | lecturer_name | class |day| start|end |
|-------------- +--------------- +--------------------+----------------|
| Electronics 2 | Jhon Rayan | Engineering Class 2| 0 | 8.5 |11.5 |
------------------------------------------------------------------------
我尝试在上表中建立有关日期的搜索页面,但是我遇到了一些问题
我在数据库中使用的日期是一个整数(0表示星期日,1表示星期一...。)
我需要在搜索面板中输入例如星期日,这意味着数据库中为0,然后获取结果并将其显示为星期日,而不是0
我用来获取结果的查询如下
$raw_results = mysql_query("SELECT lecture_name,
lecturer_name,
class,
start,
end,
CASE day
WHEN 0 THEN 'Sunday'
WHEN 1 THEN 'Monday'
WHEN 2 THEN 'Tuesday'
WHEN 3 THEN 'Wednesday'
WHEN 4 THEN 'Thursday'
WHEN 5 THEN 'Friday'
WHEN 6 THEN 'Saturday'
ELSE 'Unknown'
END AS x
FROM lecture_table WHERE (`day` LIKE '%".$name."%')") or die(mysql_error());
因此,在上述查询之前我应该使用什么来将输入搜索从周日转换为0,以将输入项与数据库进行比较。
最佳答案
您是否正在寻找这样的东西?
SELECT lecture_name, lecturer_name, class, start, end, day_name
FROM lecture_table l JOIN
(
SELECT 0 day, 'Sunday' day_name UNION ALL
SELECT 1, 'Monday' UNION ALL
SELECT 2, 'Tuesday' UNION ALL
SELECT 3, 'Wednesday' UNION ALL
SELECT 4, 'Thursday' UNION ALL
SELECT 5, 'Friday' UNION ALL
SELECT 6, 'Saturday'
) d ON l.day = d.day
WHERE day_name = 'Sunday'
输出:
| LECTURE_NAME | LECTURER_NAME | CLASS | START | END | DAY_NAME | |---------------|---------------|---------------------|-------|------|----------| | Electronics 2 | Jhon Rayan | Engineering Class 2 | 8.5 | 11.5 | Sunday |
Here is SQLFiddle demo
If you want only records for Monday
... WHERE day_name = 'Monday'
如果要记录几天
... WHERE day_name IN('Monday', 'Wednesday', 'Friday')
当然,您可以使用php变量来插入查询字符串,而不是使用确切的值,例如
$sql = "SELECT ... WHERE day_name = '$name'"; // Don't forget validate and sanitize user input
或更好地切换到PDO / mysqli并使用准备好的语句。
关于php - 从mysql获取结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24975706/