我是一名新手程序员,我想知道是否有办法以正常工作的格式纠正以下代码。 (我似乎总是搞砸语法。)
$query2 = mysql_query("SELECT IF EXISTS EmployeeName, EmployeeNumber, Position,
ManagementTraining1, ManagementTraining2, ManagementTraining3, ManagementTraining4,
ManagementTraining5, ManagementTraining6, ManagementTraining7 FROM
managementMeetingAttendance ORDER BY EmployeeNumber") or die(mysql_error());
我正在从动态创建的表中收集数据,并想知道是否存在类似于'IF EXISTS'语句的内容,可以对可能存在或可能不存在的列进行。
任何帮助将不胜感激! 谢谢!
答案 0 :(得分:0)
不,没有,但您可以先查询数据库中的列名:
select column_name from information_schema.columns where table_name=<TABLE>
答案 1 :(得分:0)
我不是mySQL的人,但我不确定你所写的声明的意图,并且根据你的意图,可能会有一个有效的答案。
你有:
SELECT IF EXISTS EmployeeName, EmployeeNumber, Position,
ManagementTraining1, ManagementTraining2, ManagementTraining3, ManagementTraining4,
ManagementTraining5, ManagementTraining6, ManagementTraining7 FROM
managementMeetingAttendance ORDER BY EmployeeNumber
由于你没有where子句,你可能不会查找特定的记录,并且使用“exists”似乎只是在询问表managementMeetingAttendance是否包含至少一条记录,其结果是列列表和按陈述的顺序是无关紧要的。
((SELECT Count(*) FROM managementMeetingAttendance) > 0)
如果表包含行,则计算结果为true,如果表没有,则计算结果为<。
但是,如果您需要确定该表是否包含列出的每个列,那么这有点复杂了
根据上一个答案,您需要使用information_schema.columns来获取表中现有的列,然后查询此数据 - 如下所示:
IF EXISTS select 1 from (
SELECT Column_Name FROM information_schema.columns
WHERE table_name = 'managementMeetingAttendance' AND column_name = 'EmployeeName'
) eName AND EXISTS select 1 from (
SELECT Column_Name FROM information_schema.columns
WHERE table_name = 'managementMeetingAttendance' AND column_name = 'EmployeeNumber'
) eNum AND EXISTS select 1 from (
SELECT Column_Name FROM information_schema.columns
WHERE table_name = 'managementMeetingAttendance' AND column_name = 'Position'
) ePos AND EXISTS select 1 from (
SELECT Column_Name FROM information_schema.columns
WHERE table_name = 'managementMeetingAttendance' AND column_name
= 'ManagementTraining1'
) eTrng1 AND EXISTS select 1 from (
etc