2017-10-11 83 views
0

我想下面的MySQL查詢轉換在Drupal 7如何轉換的MySQL連接查詢到的Drupal 7 db_select連接查詢

  SELECT ws.sid, u.name AS username, r.name AS role, 
     DATE_FORMAT(FROM_UNIXTIME(u.created), '%d-%m-%Y') AS 'created', 
     DATE_FORMAT(FROM_UNIXTIME(u.login), '%d-%m-%Y') AS 'last_login', 
     DATE_FORMAT(FROM_UNIXTIME(u.access), '%d-%m-%Y') AS 'last_accessed' 
     FROM users u 
     INNER JOIN users_roles ur ON ur.uid = u.uid 
     INNER JOIN role r ON r.rid = ur.rid 
     INNER JOIN webform_submissions ws ON ws.uid = u.uid 
     WHERE u.login <= UNIX_TIMESTAMP((NOW() - INTERVAL 1 YEAR)) AND r.name IN ('elev', 'lærer') 
     ORDER BY last_login ASC 


    Can anyone please suggest how to write it? 
+1

可以使用db_query代替db_select – Wis

+0

可以請你讓我知道如何轉換此查詢db_query? – user1755949

+0

你已經試過了什麼? drupal數據庫api被記錄[這裏](https://www.drupal.org/docs/7/api/database-api/database-api-overview) – 2pha

回答

1

使用db_query

db_query("Your query here")->fetchAll(); //output as objects 
db_query("Your query here")->fetchAll(PDO::FETCH_ASSOC); //output as arrays 

到db_select您的SQL查詢。

db_query("SELECT ws.sid, u.name AS username, r.name AS role, 
     DATE_FORMAT(FROM_UNIXTIME(u.created), '%d-%m-%Y') AS 'created', 
     DATE_FORMAT(FROM_UNIXTIME(u.login), '%d-%m-%Y') AS 'last_login', 
     DATE_FORMAT(FROM_UNIXTIME(u.access), '%d-%m-%Y') AS 'last_accessed' 
     FROM users u 
     INNER JOIN users_roles ur ON ur.uid = u.uid 
     INNER JOIN role r ON r.rid = ur.rid 
     INNER JOIN webform_submissions ws ON ws.uid = u.uid 
     WHERE u.login <= UNIX_TIMESTAMP((NOW() - INTERVAL 1 YEAR)) AND r.name IN ('elev', 'lærer') 
     ORDER BY last_login ASC")->fetchAll(PDO::FETCH_ASSOC); 
+0

我們可以在db_select中寫這個查詢嗎?因爲我不想傳遞原始的mysql查詢? – user1755949

1

在這裏你去

$query = db_query("SELECT ws.sid, u.name AS username, r.name AS role, DATE_FORMAT(FROM_UNIXTIME(u.created), '%d-%m-%Y') AS 'created', DATE_FORMAT(FROM_UNIXTIME(u.login), '%d-%m-%Y') AS 'last_login', DATE_FORMAT(FROM_UNIXTIME(u.access), '%d-%m-%Y') AS 'last_accessed' 
    FROM users u 
    INNER JOIN users_roles ur ON ur.uid = u.uid 
    INNER JOIN role r ON r.rid = ur.rid 
    INNER JOIN webform_submissions ws ON ws.uid = u.uid 
    WHERE u.login <= UNIX_TIMESTAMP((NOW() - INTERVAL 1 YEAR)) AND r.name IN ('elev', 'lærer') 
    ORDER BY last_login ASC")->fetchAll(PDO::FETCH_ASSOC); 

echo "<pre>";print_r($query);exit; //to check the result