0

I have a very simple db that has two tables, one to store a user's auth (username and pw) and one to store preferences. Currently when my app initializes, it checks for settings first and then auth. But I want to grab it all at once. The way the app is designed, there is only ever 1 record in either table, so I don't use WHERE clauses in my queries.

The problem is, when I do queries separately, they give different results than if I join them.

Consider this scenario: a user logs in, sets some settings and then logs out. In may app this causes the auth table to be cleared but the settings remain intact.

Sign-out query (just clears auth table)

db.transaction(function(tx) {
    tx.executeSql('DELETE FROM userdata');
}, errorDB);

However this outputs "0 rows found":

db.transaction(function(tx) {
    tx.executeSql('SELECT USERDATA.*, PREFS.* FROM USERDATA, PREFS', [], function (tx, results) {
         var len = results.rows.length;
        console.log(len + " rows found.");
        for (var i=0; i<len; i++){
            console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data =  " + results.rows.item(i));
        }
    }, errorDB);
}, errorDB);

Whereas this outputs a row:

db.transaction(function(tx) {
    tx.executeSql('SELECT * FROM PREFS', [], function (tx, results) {
        var len = results.rows.length;
        console.log(len + " rows found.");
        for (var i=0; i<len; i++){
            console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data =  " + results.rows.item(i));
        }
    }, errorDB);
}, errorDB);

Even if there is no auth shouldn't the join query find the prefs data? What's going on here?

4

1 回答 1

0

FROM当您在子句中列出两个表 A 和 B 时,您会得到一个cross join,它返回 A×B 记录。所以如果一张表是空的,结果也会是空的。

为了确保即使是空表也有记录,请使用UNION ALL添加另一条记录,然后使用 LIMIT 1 返回第一条记录。例如,

SELECT Name, PW FROM UserData
UNION ALL
SELECT NULL, NULL
LIMIT 1

将返回带有名称/密码的单条记录,或带有两个 NULL 值的单条记录。

要将其与另一个表连接,请使用子查询:

SELECT *
FROM (SELECT Name, PW FROM UserData
      UNION ALL
      SELECT NULL, NULL
      LIMIT 1),
     Prefs
于 2013-10-18T16:37:03.407 回答