用于检查多个字段的MYSQL字符串

时间:2014-04-25 06:49:29

标签: php mysql

在插入新行之前,我正在尝试根据四条信息检查数据库中是否存在类似的条目。如果例如存在相同的名称,则可以,但如果名称,纬度/经度和时间都相同则不行。这是我的代码:

$query3 = "INSERT INTO locations
(
Name,
Time,
Area,
Latitude,
Longitude,
Current,
Previous,
Destination
)
SELECT * FROM
(
SELECT Name, Time, Area, Latitude, Longitude, Current, Previous, Destination) AS tmp
WHERE NOT EXISTS
(
    SELECT  Name, Latitude, Longitude, Time FROM
    locations
    WHERE Name = '$Name' AND Latitude = '$latitude' AND Longitude = '$longitude' AND Time = '$timereceived')
";

我目前所提出的错误是

Could not connect: Unknown column 'Name' in 'field list'

我不明白错误信息,我想我的MYSQL字符串中有语法错误。非常感谢你提前!

1 个答案:

答案 0 :(得分:0)

您的查询完全搞砸了。 您使用单引号作为列名称,并在某处使用反引号作为值,并在某处使用列名称中的变量

在查询中使用

$Name, $timereceived, $area, $latitude, $longitude, $currentport, $previousport, $destination

如果不在查询

中直接使用列名,我猜这些变量会保留列名

应该看起来像

$query3 = "INSERT INTO locations 
(
Name, 
Time, 
Area, 
Latitude, 
Longitude, 
Current, 
Previous, 
Destination
)
SELECT * FROM 
(
    SELECT $Name, $timereceived, $area, $latitude, $longitude, $currentport, $previousport, $destination) AS tmp
    WHERE NOT EXISTS 
    (
        SELECT  Name, Latitude, Longitude, Time FROM 
        locations
        WHERE Name = '$Name' AND Latitude = '$latitude' AND Longitude = '$longitude' AND Time = '$timereceived')
";

<强>更新 查询不正确,此处缺少别名是一个应该起作用的查询

INSERT INTO locations 
( 
  Name, 
  Time, 
  Area, 
  Latitude, 
  Longitude, 
  Current, 
  Previous, 
  Destination 
) 
SELECT * FROM 
( 
  SELECT 
  Name, 
  Time, 
  Area, 
  Latitude, 
  Longitude, 
  Current, 
  Previous, 
  Destination
  from locations 
)l1
WHERE 
NOT EXISTS 
( 
  SELECT 
  1 
  FROM locations l2
  WHERE 
  l2.Name = 'Ocean' 
  AND l2.Latitude = '145.717' 
  AND l2.Longitude = '-16.6365' 
  AND l2.Time = '2014-04-23 13:45'
);

<强> DEMO

<强> UPDATE2 霍华德克劳斯有一些问题,多次添加数据,所以他应用的修复

INSERT INTO locations 
(Name, Area, Latitude, Longitude, Current, Previous, Destination, Time) 
SELECT a.Name, a.Area, a.Latitude, a.Longitude, a.Current, a.Previous, a.Destination, a.Time 
FROM ( 
SELECT  Name, Area, Latitude, Longitude, Current, Previous,  Destination, Time) a 
WHERE NOT EXISTS ( 
SELECT 1 FROM locations WHERE Name= '$Name' AND Longitude = '$longitude'
); 
相关问题