将两个查询合并为一个条件不同的查询

时间:2019-11-27 10:50:40

标签: mysql sql sql-server select

如果分为两个查询,我们将获得正确的结果。

SELECT * FROM table_name
WHERE field_1 = 'name_1' AND (field_2) IN ('123', '456', '345');

SELECT * FROM table_name
WHERE field_1 = 'name_2' AND (field_2) IN ('456', '876', '548', '111');

但是如何将这两个查询合并为一个。可能会有两个以上的请求。

4 个答案:

答案 0 :(得分:2)

如果您在“ WHERE”子句中使用“我们”或“ OR”,则可以在一个查询中执行此操作

['/1.js', '/2.js',  '/3.js', '/4.js', '/5.js'].forEach(function(script) {
    var scriptElement = document.createElement("script");
    scriptElement.src = script;

    // append script element where you want (head or body)
    document.head.appendChild(scriptElement);
});

答案 1 :(得分:1)

使用OR:

var codes = [

    ['2', '12521', '3'],
    ['3', '32344', '2'],
    ['3', '35213', '2'],
    ['4', '42312', '2'],
    ['4', '41122', '1'],
    ['5', '51111', '1']

];
    
const output = codes.reduce(({result, current}, [x, ...y]) => {
  if (current !== x) result.push([]);
  result[result.length - 1].push([x, ...y]);
  
  return {result, current: x};
}, {result: []}).result;

console.log(output);

答案 2 :(得分:1)

U可以通过以下方法实现。

方法1:

  SELECT field_1 ,field_2 FROM table_name
  WHERE  (field_1 = 'name_1' AND (field_2) IN ('123', '456', '345')
         ) OR 
         (
          field_1 = 'name_2' AND (field_2) IN ('456', '876', '548','111')
         )

方法2:

SELECT field_1 ,field_2 FROM table_name
WHERE  (field_1 = 'name_1' AND  (field_2) IN ('123', '456', '345')         
UNION              
SELECT field_1 ,field_2 FROM table_name

WHERE field_1 = 'name_2' AND (field_2) IN ('456', '876','548','111')

答案 3 :(得分:0)

如果仍然需要输出。

然后在查询之间放置UNION