我想构建一个查询来返回已登录用户的项目ID列表,将最新的排序到最近的最近?
我有2个MySQL表:
这是我到目前为止所得到的:
SELECT project_id FROM project_access WHERE member_id='" . $_SESSION["myid"] . "' ORDER BY updated DESC"
'updated'实际上在另一个表中。如何将其写入查询?
由于
答案 0 :(得分:1)
您使用JOIN子句,如下所示:
SELECT projects.project_id, projects.updated
FROM project_access
INNER JOIN projects
ON project_access.project_id=projects.project_id
WHERE project_access.member_id='" . $_SESSION["myid"] . "'
ORDER BY projects.updated DESC
注意:您应该阅读有关JOIN子句的信息:
http://dev.mysql.com/doc/refman/5.0/en/join.html
..上述查询可能适用与否,具体取决于您的要求和表格结构。
在处理SQL语句时,还应确保正确转义字符串,以避免SQL注入攻击:
http://php.net/manual/en/function.mysql-real-escape-string.php
http://en.wikipedia.org/wiki/SQL_injection
您的代码应为:
WHERE project_access.member_id='" . mysql_real_escape_string($_SESSION["myid"]) . "'
(我假设您在这里使用PHP)。
SQL JOIN教程:
答案 1 :(得分:1)
这将做你的事后。
"SELECT
projects.project_id
FROM project_access
INNER JOIN projects ON (project_access.project_id = projects.project_id)
WHERE project_access.member_id='" . $_SESSION["myid"] . "'
ORDER BY projects.updated DESC"
我建议你阅读一些基本的查询教程,特别是关于连接。这个应该有用http://www.sql-tutorial.net/SQL-JOIN.asp