From 12ac6f756e26d1eba346828a6ceb18a4decac1f4 Mon Sep 17 00:00:00 2001 From: gphp0071201 Date: Tue, 22 Dec 2020 14:26:46 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0join=E6=96=B9=E6=B3=95,?= =?UTF-8?q?=E5=B9=B6=E6=89=93=E5=8C=85=E7=94=9F=E4=BA=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SUMMARY.md | 1 + build/common.js | 2 +- build/uitl.js | 2 +- docs/chain/join.md | 40 +++++++++++++++++++++++++++++++++ docs/chain/table.md | 9 ++++++++ index.js | 22 ++++++++++++++++-- package.json | 2 +- src/common.js | 55 ++++++++++++++++++++++++++++++++++++++++----- src/uitl.js | 32 ++++++++++++++------------ 9 files changed, 140 insertions(+), 25 deletions(-) create mode 100644 docs/chain/join.md diff --git a/SUMMARY.md b/SUMMARY.md index 8f97f97..1574157 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -19,6 +19,7 @@ * [2.12.DISTINCT](/docs/chain/distinct.md) * [2.13.LOCK](/docs/chain/lock.md) * [2.14.COMMENT](/docs/chain/comment.md) + * [2.14.JOIN](/docs/chain/join.md) * [3.CURD调用](/docs/curd/README.md) * [3.1.SELECT](/docs/curd/select.md) * [3.2.UPDATE](/docs/curd/update.md) diff --git a/build/common.js b/build/common.js index 32edc14..872828a 100644 --- a/build/common.js +++ b/build/common.js @@ -1 +1 @@ -"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _keys=require("babel-runtime/core-js/object/keys"),_keys2=_interopRequireDefault(_keys),_getIterator2=require("babel-runtime/core-js/get-iterator"),_getIterator3=_interopRequireDefault(_getIterator2),_typeof2=require("babel-runtime/helpers/typeof"),_typeof3=_interopRequireDefault(_typeof2);exports.table=table,exports.where=where,exports.field=field,exports.alias=alias,exports.data=data,exports.order=order,exports.limit=limit,exports.page=page,exports.group=group,exports.having=having,exports.union=union,exports.distinct=distinct,exports.lock=lock,exports.comment=comment,exports.count=count,exports.max=max,exports.min=min,exports.avg=avg,exports.sum=sum;var _uitl=require("./uitl.js");function _interopRequireDefault(t){return t&&t.__esModule?t:{default:t}}function table(t){return t&&-1!=t.indexOf("SELECT")&&(t="("+t+")"),t&&(this.sqlObj.table=t),this}function where(t){var e="";return(e="string"==typeof t?t:(0,_uitl.getOptToString)(t))&&(this.sqlObj.where=e),this}function field(t){if("object"===(void 0===t?"undefined":(0,_typeof3.default)(t))){var e=[],i=!0,r=!1,n=void 0;try{for(var s,o=(0,_getIterator3.default)(t);!(i=(s=o.next()).done);i=!0){var u=s.value;if("string"==typeof u)e.push(u);else{var l=(0,_keys2.default)(u),a=!0,h=!1,f=void 0;try{for(var p=(0,_getIterator3.default)(l);!(a=(c=p.next()).done);a=!0){var c=c.value;e.push(c+" AS "+u[c])}}catch(t){h=!0,f=t}finally{try{!a&&p.return&&p.return()}finally{if(h)throw f}}}}}catch(t){r=!0,n=t}finally{try{!i&&o.return&&o.return()}finally{if(r)throw n}}t=e.join(", ")}return this.sqlObj.field=t,this}function alias(t){return this.sqlObj.alias=t,this}function data(t){var e={};return"string"==typeof t?t.split("&").forEach(function(t){t=t.split("=");e[t[0]]=t[1]}):e=t,this.sqlObj.data=e,this}function order(t){return"object"===(void 0===t?"undefined":(0,_typeof3.default)(t))&&(t=t.join(",")),this.sqlObj.order="ORDER BY "+t,this}function limit(){return this.sqlObj.limit="LIMIT "+Array.prototype.slice.apply(arguments),this}function page(t){var e=[];return 2==(e=1===arguments.length?t.split(","):Array.prototype.slice.apply(arguments)).length&&(t=parseInt(e[0]-1)*parseInt(e[1]),e=parseInt(e[1]),this.sqlObj.limit="LIMIT "+t+","+e),this}function group(t){return this.sqlObj.group="GROUP BY "+t,this}function having(t){return this.sqlObj.having="HAVING "+t,this}function union(t){var e=1"+checkOptType(r)+")";break;case"GT":a="("+e+">"+checkOptType(r)+")";break;case"EGT":a="("+e+">="+checkOptType(r)+")";break;case"LT":a="("+e+"<"+checkOptType(r)+")";break;case"ELT":a="("+e+"<="+checkOptType(r)+")";break;case"LIKE":a="("+e+" LIKE "+checkOptType(r)+")";break;case"NOTLIKE":a="("+e+" NOT LIKE "+checkOptType(r)+")";break;case"BETWEEN":a="("+e+" BETWEEN "+r.replace(","," AND ")+")";break;case"NOTBETWEEN":a="("+e+" NOT BETWEEN "+r.replace(","," AND ")+")";break;case"IN":a="("+e+" IN ("+r+"))";break;case"NOTIN":a="("+e+" NOT IN ("+r+"))";break;default:a="("+e+"="+checkOptType(r)+")"}return p?a+" ":a+" "+c+" "}function sortSelectSql(e){e=e||{};(e.count||e.max||e.min||e.avg||e.sum)&&(t=(e.count?","+e.count:"")+(e.max?","+e.max:"")+(e.min?","+e.min:"")+(e.avg?","+e.avg:"")+(e.sum?","+e.sum:""),e.count=e.max=e.min=e.avg=e.sum="",e.field?e.field=e.field+t:e.field=t.substring(1)),e.field||(e.field="*"),e.table&&(e.table="FROM "+e.table),e.where&&(e.where="WHERE "+e.where);var t=(0,_keys2.default)(e),c=[],p=["union","distinct","field","count","max","min","avg","sum","table","alias","where","group","having","order","limit","page","comment"];return t.forEach(function(r,e){p.forEach(function(e,t){r===e&&(c[t]=r)})}),{sortkeys:c,result:e}}function sortArray(e){for(var t=[],r=(0,_keys2.default)(e[0]),c=1;c"+checkOptType(r)+")";break;case"GT":p="("+e+">"+checkOptType(r)+")";break;case"EGT":p="("+e+">="+checkOptType(r)+")";break;case"LT":p="("+e+"<"+checkOptType(r)+")";break;case"ELT":p="("+e+"<="+checkOptType(r)+")";break;case"LIKE":p="("+e+" LIKE "+checkOptType(r)+")";break;case"NOTLIKE":p="("+e+" NOT LIKE "+checkOptType(r)+")";break;case"BETWEEN":p="("+e+" BETWEEN "+r.replace(","," AND ")+")";break;case"NOTBETWEEN":p="("+e+" NOT BETWEEN "+r.replace(","," AND ")+")";break;case"IN":p="("+e+" IN ("+r+"))";break;case"NOTIN":p="("+e+" NOT IN ("+r+"))";break;default:p="("+e+"="+checkOptType(r)+")"}return a?p+" ":p+" "+c+" "}function sortSelectSql(e){e=e||{};1 或 object类型, 例如: + + +Array类型参数 +```js +sql.table('node_table').join([{ + dir: 'left', + table: ('left_table'), + where: [{'node_talbe.id': ['join_table.id']}] +}, { + dir: 'right', + table: ('right_table'), + where: [{'right_table.id': ['left_table.id']}] +}]).where('node_table.id=1').select() +``` + +最终得到 +```js +SELECT * FROM node_table LEFT JOIN left_table ON ((node_talbe.id=join_table.id) ) RIGHT JOIN right_table ON ((right_table.id=left_table.id) ) WHERE node_table.id=1 +``` + +object类型参数 +```js +sql.table('node_table').join({ + dir: 'left', + table: ('left_table'), + where: [{'node_talbe.id': ['join_table.id']}] +}).where('node_table.id=1').select() +``` + +最终得到 +```js +SELECT * FROM node_table LEFT JOIN left_table ON ((node_talbe.id=join_table.id) ) WHERE node_table.id=1 +``` + diff --git a/docs/chain/table.md b/docs/chain/table.md index 574bf6f..fbf898c 100644 --- a/docs/chain/table.md +++ b/docs/chain/table.md @@ -16,5 +16,14 @@ SELECT * FROM node_table a WHERE id=1 ``` +多表同时查询: +```js +sql.table({'node_table1': 'a', 'node_table2': 'b'}).where('id=1').select() +``` +得到: +``` +SELECT * FROM node_table1 AS a, node_table2 AS b WHERE id=1 +``` + join方法还需要补充... \ No newline at end of file diff --git a/index.js b/index.js index 1867d49..3365ee0 100644 --- a/index.js +++ b/index.js @@ -88,9 +88,27 @@ console.log(insertSql) content.innerHTML = `${insertSql1}
${insertSql}`; console.group('普通查询语句') -console.log(sql.table('atables').field('id, name, hello_boy').select()) +console.log(sql.table({'user': 'a', 'menu': 'b'}).select()) +console.log(sql.table({'gp_table1': 'a', 'gp_table2': 'b'}).join({ + dir: 'left outer', + table: 'hello', + where: [{'a.id': ['hello.id'], 'b.id': ['hello.id'], _type: 'or', _nexttype: 'or'}, {'hello.name': ['b.name']}] +}).field('id, name, hello_boy').select()) console.groupEnd() - +console.log(sql.table('node_table').group('user_id').join({ + dir: 'left', + table: ('join_table'), + where: [{'node_talbe.id': ['join_table.id']}] +}).where('id=1').having('count(number)>3').select(), '516516516516') +console.log(sql.table('node_table').join([{ + dir: 'left', + table: ('left_table'), + where: [{'node_talbe.id': ['join_table.id']}] +}, { + dir: 'right', + table: ('right_table'), + where: [{'right_table.id': ['left_table.id']}] +}]).where('node_table.id=1').select(), '516516516516') console.group('数组类型') console.log('Array', sql.table('atables').field(['a.id', 'name', 'hello_boy', 'remarks']).select()) console.log('Array', sql.table('atables a, btables b').field(['id', 'name', { 'a.hello_boy': 'helloBoy', 'b.user_id': 'userId' }, 'remarks']).select()) diff --git a/package.json b/package.json index dbb9f28..9317107 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "node-mysqls", - "version": "0.0.3", + "version": "0.0.5", "description": "快速生成mysql语句", "main": "./build/main.js", "keywords": [ diff --git a/src/common.js b/src/common.js index 6e0db8a..96bbd65 100644 --- a/src/common.js +++ b/src/common.js @@ -2,15 +2,32 @@ import { getOptToString, checkOptType, checkOptObjType, - expressionQuery + expressionQuery, + sortSelectSql } from './uitl.js' -//需要查询的table表 参数:String 案例:table('user') -export function table(opt){ - if(opt&&opt.indexOf('SELECT')!=-1){ - opt = `(${opt})` +// 需要查询的table表 参数:String, object +// 案例:String table('user') +/** + * 需要查询的table表 参数: string, object + * 案例: string: table('user') + * object: table({'user_name': 'a', 'user_b': 'b'}) + * @param {*} opt + */ +export function table (opt) { + if (typeof opt === 'string') { + if(opt&&opt.indexOf('SELECT')!=-1){ + opt = `(${opt})` + } + if(opt) this.sqlObj.table = opt + } else { + const keys = Object.keys(opt) + let arr = [] + for (const k of keys) { + arr.push(`${k} AS ${opt[k]}`) + } + this.sqlObj.table = arr.join(', ') } - if(opt) this.sqlObj.table = opt return this; } @@ -29,6 +46,32 @@ export function where(opt){ return this; } +/** + * @param {Array|object} opt join参数 + * opt.dir 连接方向 + * opt.table 连接表名 + * opt.where 连接条件 + */ + +export function join(opt) { + let result = '' + switch (Object.prototype.toString.call(opt)) { + case '[object Array]': + for (let i = 0, len = opt.length; i < len; i++) { + if (!opt[i].dir || !opt[i].table || !opt[i].where) continue + result += ` ${opt[i].dir.toUpperCase()} JOIN ${sortSelectSql(opt[i].table, true).result} ON ${getOptToString(opt[i].where)}` + } + break; + case '[object Object]': + if (!opt.dir || !opt.table || !opt.where) return + result += ` ${opt.dir.toUpperCase()} JOIN ${sortSelectSql(opt.table, true).result} ON ${getOptToString(opt.where)}` + break + default: + break; + } + if (result) this.sqlObj.join = result + return this +} /*查询字段 参数为 String | Array 案例: String field('id,name,age,sex') | field(['id','name','age','sex']) diff --git a/src/uitl.js b/src/uitl.js index 98f530d..43114fd 100644 --- a/src/uitl.js +++ b/src/uitl.js @@ -157,26 +157,30 @@ export function expressionQuery(par_key,chi_key,value,_type,isLastOne){ } //排序 生成 sql 字符串 -export function sortSelectSql(json){ +export function sortSelectSql(json, bool = false){ let result = json || {} - if(result.count||result.max||result.min||result.avg||result.sum){ - let concatstr=(result.count?`,${result.count}`:'') - +(result.max?`,${result.max}`:'') - +(result.min?`,${result.min}`:'') - +(result.avg?`,${result.avg}`:'') - +(result.sum?`,${result.sum}`:'') - result.count=result.max=result.min=result.avg=result.sum=''; - result.field? result.field = (result.field+concatstr) : result.field = concatstr.substring(1) - } - if(!result.field)result.field = '*' - if(result.table) result.table = `FROM ${result.table}` - if(result.where) result.where = `WHERE ${result.where}` + if (bool) { + if(result.table) result.table = `${result.table}` + } else { + if(result.count||result.max||result.min||result.avg||result.sum){ + let concatstr=(result.count?`,${result.count}`:'') + +(result.max?`,${result.max}`:'') + +(result.min?`,${result.min}`:'') + +(result.avg?`,${result.avg}`:'') + +(result.sum?`,${result.sum}`:'') + result.count=result.max=result.min=result.avg=result.sum=''; + result.field? result.field = (result.field+concatstr) : result.field = concatstr.substring(1) + } + if(!result.field)result.field = '*' + if(result.table) result.table = `FROM ${result.table}` + if(result.where) result.where = `WHERE ${result.where}` + } let keys = Object.keys(result) let keysresult = [] // 查询默认排序数组 let searchSort = ['union','distinct','field','count','max','min','avg','sum','table', - 'alias','where','group','having','order','limit','page','comment'] + 'alias', 'join', 'where','group','having','order','limit','page','comment'] //排序 keys.forEach((item1,index1)=>{ searchSort.forEach((item2,index2)=>{