How to reformulate an sql query

旧巷老猫 提交于 2020-01-17 04:07:06

问题


i am not an expert in sql programming and i was wondering if you can help me reformulate the following query using 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 ."))");

回答1:


Would something like this work?

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



回答2:


Assuming your field_date_and_time table has a column called uid having the same meaning as that column in your node table, here's what you need to do.

      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."'

Beware SQL injection attacks! Avoid substituting variables directly into SQL statements unless you're really sure those variables can't be corrupted by badguy users! Remember the story of the guy named

"johnny ; drop tables *;" 


来源:https://stackoverflow.com/questions/17655988/how-to-reformulate-an-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!