私はかなり風変わりな質問があります。 SELECT
文ではデフォルト値を設定できますか?
次のクエリでは、 boolItem
を常にfalse(データベースから取得しない)にします。なぜ私は説明するので、私は知っているが、私には耐えられない。
SELECT id, boolItem = False
FROM MyTable;
私は既存の大規模なSQLデータベースとプロジェクトを扱っています。私はデータを照会して、それらをAction
C#オブジェクトとして返しています。アクションは、ユーザーまたは標準のアクションによってカスタム化できます。これはIsCustom
プロパティによって示されます。
public class Action
{
public int Id { get; set; }
public bool IsCustom { get; set; }
.....
}
SQLデータベースにカスタムアクションは、テーブルに格納されているcustom_actions
と標準アクションは、テーブルにあるactions
。
以下のコードを使用してAction
オブジェクトを取得して保存します。私はactions
テーブルのクエリを常にプロパティIsCustom
をfalseに設定したいと思っています。また、 custom_actions
テーブルのクエリは、常にIsCustom
プロパティをtrueに設定します。私はクエリを使用していますSELECT a.id AS Id, a.is_custom = false AS IsCustom
は有効なコードではありません。テーブルにはis_custom
カラムがなく、何をしようとしているかを示すためです。
public async Task<IEnumerable<Models.Action>> ExecuteAsync (IDbConnection conn, IDbTransaction transition, long userId)
{
string sql = @"SELECT a.id AS Id, a.is_custom = false AS IsCustom
FROM actions a
INNER JOIN members_actions ma ON a.id = ma.action_id AND is_custom = false
WHERE ma.member_id = :userId
UNION
SELECT a.id AS Id, a.is_custom = true AS IsCustom
FROM custom_actions a
INNER JOIN members_actions ma ON a.id = ma.action_id AND is_custom = true
WHERE ma.member_id = :userId;";
return await conn.QueryAsync<Models.Action> (sql, new {userId = userId}, transition);
}
テーブル 'アクション'列= id || description || name
テーブル 'Custom_actions'列= id || description || name || parameters
これは可能ですか?構造的にデータベースを変更する(2つのテーブルを1にマージしてis_custom
カラムを追加する)よりも優れています。
true
またはfalse
の値を選択し、エイリアスを使用して列名を指定することができますIsCustom
たとえば、以下の例を変更して(そして、どちらのテーブルにもis_custom
列がないと思われるため、JOIN条件からAND is_custom = false/true
削除しました)
public async Task<IEnumerable<Models.Action>> ExecuteAsync (IDbConnection conn, IDbTransaction transition, long userId)
{
string sql = @"SELECT a.id AS Id, false AS IsCustom
FROM actions a
INNER JOIN members_actions ma ON a.id = ma.action_id
WHERE ma.member_id = :userId
UNION
SELECT a.id AS Id, true AS IsCustom
FROM custom_actions a
INNER JOIN members_actions ma ON a.id = ma.action_id
WHERE ma.member_id = :userId;";
return await conn.QueryAsync<Models.Action> (sql, new {userId = userId}, transition);
}