0

我正在尝试从名为 address_contact 的表中获取最后一个 ID#,我使用的代码是:

$result = mysql_query("SELECT id FROM address_contact ORDER BY lastUpdate DESC LIMIT 1") 
or die(mysql_error());  
$row = mysql_fetch_array( $result );
$id = .$row['id'];

现在我想关闭该连接并打开一个新连接,然后使用我们刚刚获得的 ID# 从以下 3 个表中获取所有数据:

Table 1: address_address
Table 2: address_contact
Table 3: address_email

所以它看起来像这样???

$result = mysql_query("SELECT address_contact.id,address_contact.lastname,address_contact.firstname,address_contact.primaryAddType,address_address.id,address_address.phone1,address_address.phone2,address_address.line2,address_email.id,address_email.email
FROM address_address
LEFT JOIN address_contact ON address_address.id=address_contact.id 
LEFT JOIN address_email ON address_address.id=address_email.id                  
WHERE address_contact.id = ".$id)

但是必须有一种更简单/更快的方法来做到这一点?

4

3 回答 3

2

如果此 ID 用于您刚刚插入的全新记录,则您应该使用该msyql_last_insert_id()函数,它保证您获得最后一次插入此特定脚本/数据库句柄所做的操作。您的方法受竞赛条件的影响 - 如果某个 OTHER 脚本在该脚本的后面插入,您将获得该脚本的 ID,而不是您的 ID。

话虽如此,你最好还是这样做

从您的表中选择 max(id)

而不是 order by/limit 版本。这种方式对它更有效。

基本的代码序列将是:

INSERT INTO yourtable ....
SELECT @id := last_insert_id();
SELECT ... FROM yourtable WHERE id = @id;
于 2013-07-24T15:20:33.827 回答
0

您可以使用子查询在单个 SQL 语句中执行此操作以查找 ID。

SELECT
  address_contact.id,
  address_contact.lastname,
  address_contact.firstname,
  address_contact.primaryAddType,
  address_address.id,
  address_address.phone1,
  address_address.phone2,
  address_address.line2,
  address_email.id,
  address_email.email
FROM
  address_address
  LEFT JOIN address_contact ON address_address.id = address_contact.id 
  LEFT JOIN address_email   ON address_address.id = address_email.id                  
  WHERE address_contact.id = (
    SELECT id FROM address_contact ORDER BY lastUpdate DESC LIMIT 1
  )
于 2013-07-24T15:21:09.923 回答
0

Why not use single query

SELECT address_contact.id,address_contact.lastname,address_contact.firstname,address_contact.primaryAddType,address_address.id,address_address.phone1,address_address.phone2,address_address.line2,address_email.id,address_email.email
FROM address_address
LEFT JOIN address_contact ON address_address.id=address_contact.id 
LEFT JOIN address_email ON address_address.id=address_email.id                  
ORDER BY address_contact.lastUpdate DESC 
LIMIT 1
于 2013-07-24T15:28:45.237 回答