如何重新构造一个SQL查询

时间:2013-07-15 13:55:08

标签: mysql sql select inner-join

我不是sql编程方面的专家,我想知道你是否可以帮助我使用INNER JOIN重构以下查询?

db_query("
    select max(field_date_and_time_value2) as last_time 
    from field_data_field_date_and_time 
    where (field_date_and_time_value2 > '".$today."') 
    AND (".$node->uid." = (select uid from node where nid = " . $node->nid ."))");

2 个答案:

答案 0 :(得分:0)

这样的事情会起作用吗?

SELECT
    max(a.field_date_and_time_value2) as last_time
    , b.uid
FROM field_data_field_date_and_time a
    INNER JOIN
        node b
    ON
        /* this piece might be wrong. what is the relationship between the first table and the second one? */
        b.nid = '".$node->nid."'
where
    a.field_date_and_time_value2 > '".$today."' AND
    b.uid = $node->nid

答案 1 :(得分:0)

假设您的field_date_and_time表格中有一个名为uid的列与您的node表格中的列具有相同的含义,那么您需要执行以下操作。

      SELECT MAX(A.field_date_and_time_value2) AS last_time
        FROM field_date_and_time A
  INNER JOIN node B ON A.uid = B.uid
       WHERE B.nid = '".$node->nid."'
         AND A.field_date_and_time_value2 > '".$today."'

小心SQL注入攻击!避免将变量直接替换为SQL语句,除非您确定这些变量不会被badguy用户破坏!记住这个名叫

的人的故事
"johnny ; drop tables *;"