如何将2个SQL查询放在一起?

时间:2016-01-11 09:12:33

标签: php mysql sql input

我试图将2个SQL查询一个用于名称:

$query = "SELECT * FROM register WHERE name LIKE '" .$name ."'ORDER BY id DESC";

和一个得到$和$到:

$sql = "SELECT * FROM register WHERE time BETWEEN ('$from') AND ('$to')";

您能否建议如何将这两个查询组合起来,以显示所选择的名称以及从中选择的名称,以及仅显示所选名称的所有结果,而不显示from和to?

6 个答案:

答案 0 :(得分:1)

您可以使用Union来合并两个查询的结果

SELECT * FROM register WHERE name LIKE '" .$name ."'
union all
SELECT * FROM register WHERE time BETWEEN ('$from') AND ('$to')

答案 1 :(得分:1)

SELECT * FROM register WHERE time BETWEEN @from AND @to
UNION
SELECT * FROM register WHERE name LIKE @name ORDER BY id DESC

答案 2 :(得分:1)

可以使用UNION完成此操作,也可以使用OR条件:

SELECT *
FROM register
WHERE name LIKE '" .$name ."'
    OR time BETWEEN ('$from') AND ('$to')
ORDER BY id DESC;

答案 3 :(得分:1)

    SELECT * FROM register WHERE name LIKE '" .$name ."' 
          OR time BETWEEN ('$from') AND ('$to')
    ORDER BY id DESC

答案 4 :(得分:0)

你的问题不清楚但仍可以尝试这样的事情

$query = "SELECT * FROM register WHERE name LIKE '" .$name ."'
OR (time BETWEEN ('$from') AND ('$to')) ORDER BY id DESC";

答案 5 :(得分:0)

这就是我所追求的,感谢我的Oracle程序员,你知道你是谁,我想分享:

$query = "SELECT * FROM register WHERE name LIKE '" .$name ."' and time between ifnull(timestamp('$from'),time) and ifnull(timestamp('$to'),time) ORDER BY id DESC";